从RC2迁移到1.0:从控制器操作返回“动态”会导致奇怪的Web api响应

时间:2016-07-15 12:48:25

标签: asp.net-core asp.net-core-1.0

我最近从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": { }
  },

2 个答案:

答案 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]);