Web API method return JSON data

11,992

You can use the Json<T>(T content) method of the ApiController

public async Task<IHttpActionResult> GetPartnerList() {
    List<Partner> data = await _context.Partners.Take(100).ToListAsync();
    return Json(data);
}

refactor action to return IHttpActionResult abstraction, await the data and pass it to the Json method which returns a JsonResult.

This means that regardless of content negotiation, the above action will only return JSON data.

Share:
11,992
Karan
Author by

Karan

Coding is fun ! Lets Enjoy it.

Updated on July 08, 2022

Comments

  • Karan
    Karan almost 2 years

    I am using ASP.net web API 2.0 and would like my method to return the data in JSON format only.

    Please suggest the code changes for this below method from the API controller class.

    public async Task<List<Partner>> GetPartnerList()
    {
        return await _context.Partners.Take(100).ToListAsync();
    }
    
  • Karan
    Karan almost 6 years
    Now i realize, the Web-API framework converts the result object into the JSON data by default.
  • Karan
    Karan almost 6 years
    Content negotiation is going to happen. In my case, i have limit the WebAPIConfig class to only use the JsonFormatter and have removed the XMLFormatter.
  • Karan
    Karan almost 6 years
    But i would like to have your expert opinion, which return type i should be using. Task<IHttpActionResult> OR Task<List<Partner>> . Please suggest.
  • Nkosi
    Nkosi almost 6 years
    @Karan As you said, that is a matter of opinion. The syntax usually suggested in documentation is the abstraction approach with IHttpActionResult.