Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API method return JSON data

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();
}
like image 203
Karan Avatar asked May 07 '18 09:05

Karan


People also ask

How do I return data from Web API?

Learn the three ways you can return data from your ASP.NET Core Web API action methods. We have three ways to return data and HTTP status codes from an action method in ASP.NET Core. You can return a specific type, return an instance of type IActionResult, or return an instance of type ActionResult.

What format does Web API return data to?

By default Web API returns result in XML format.


1 Answers

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.

like image 190
Nkosi Avatar answered Oct 20 '22 23:10

Nkosi