发布:2021/9/17 13:55:00作者:管理员 来源:本站 浏览次数:1265
我正在使用ASP.net Web API 2.0,希望我的方法仅返回JSON格式的数据.
请在API控制器类中建议以下方法的代码更改.
public async Task<List<Partner>> GetPartnerList()
{
return await _context.Partners.Take(100).ToListAsync();
}
解决方案
您可以使用 Json<T>(T content) 方法ApiController
public async Task<IHttpActionResult> GetPartnerList() {
List<Partner> data = await _context.Partners.Take(100).ToListAsync();
return Json(data);
}
重构动作以返回IHttpActionResult抽象,等待数据并将其传递给Json方法,该方法返回JsonResult.
这意味着无论内容协商如何,上述操作只会返回JSON数据.
原文
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();
}
解决方案
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.
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4