Web API method return JSON data

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-03 17:20:24

问题


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();
}

回答1:


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.



来源:https://stackoverflow.com/questions/50211474/web-api-method-return-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!