我最近从RC2迁移到1.0,我遇到了关于web api响应的问题。
行动
public dynamic GetCountries(string startsWith)
{
return Ok(_countryService.GetList(startsWith));
}
RC2中的Json响应
[{
"CountryCode": "ANG",
"CountryName": "Angola"
},
{
"CountryCode": "ANT",
"CountryName": "Antigua and Barbuda"
}]
1.0中的Json响应
{
"value": [
{
"countryCode": "ANG",
"countryName": "Angola"
},
{
"countryCode": "ANT",
"countryName": "Antigua and Barbuda"
}],
"formatters": [],
"contentTypes": [],
"declaredType": null,
"statusCode": 200
}
动态类型1.0中的响应添加了对象包装器,而以前的情况并非如此,而属性较低的是驼峰。 迁移时我有些错误吗?
Project.json
"dependencies": {
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.0",
"Microsoft.AspNetCore.Razor.Tools": {
"version": "1.0.0-preview1-final",
"type": "build"
},
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.IdentityModel.Tokens": "5.0.0",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0",
},
"tools": {
"Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"net461": { }
},
答案 0 :(得分:3)
这是一个众所周知的问题:https://github.com/aspnet/Mvc/issues/4960
为什么您希望返回类型为dynamic
?为什么不返回IActionResult
?
上述问题的建议解决方法,或者您只需将返回类型更改为IActionResult
public class Fix4960ActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context) { }
public void OnActionExecuted(ActionExecutedContext context)
{
var objectResult = context.Result as ObjectResult;
if (objectResult?.Value is IActionResult)
{
context.Result = (IActionResult)objectResult.Value;
}
}
}
答案 1 :(得分:2)
这确实是来自aspnet团队的bug
。
https://github.com/aspnet/Mvc/issues/4960
感谢Kiran指出问题链接。
这已被声明为done
,但不在当前版本1.0
中,且只能在1.1.0
上使用。但是,由于1.0.1
尚未发布,因此1.0.1
版本可能可用。
直到然后使用IActionResult
是唯一的方法。
return Ok([dynamic object]);