【问题标题】:Statuscode 406 (Not Acceptable) in ASP.NET CoreASP.NET Core 中的状态码 406(不可接受)
【发布时间】:2017-05-28 15:56:28
【问题描述】:

REST 服务应该提供内容协商。这意味着客户端发送一个 Accept 标头,其中包含所需的响应内容类型。如果服务不支持这种媒体类型,它应该以状态码 406(不可接受)进行响应。

我尝试将此行为映射到 ASP.NET Core。如果 ASP.NET 核心无法识别 Accept 标头中的媒体类型,它会返回一个 JSON 文档。在以前版本的框架中,可以通过在配置中添加特殊的输出格式化程序来实现上述行为:

public void ConfigureServices(IServiceCollection services) {
  services.AddMvc(options => {
    options.OutputFormatters.Insert(0, new HttpNotAcceptableOutputFormatter());
  });
}

不幸的是,HttpNotAcceptableOutputFormatter 在 RC1 之后已从 ASP.NET Core 框架中删除。在当前版本的框架中有没有这个类的替代品?

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    我以前有过这个:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }
    

    然后我把它改成AddMvcCore()而不是AddMvc()

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore();
    }
    

    最后我遇到了响应 406 的问题,所以我所做的就是将 .AddJsonFormatters() 添加到 services.AddMVCCore() 并且我的 API 再次工作。

    public void ConfigureServices(IServiceCollection services)
    {
       services.AddMvcCore()
            .AddJsonFormatters();
    }
    

    【讨论】:

      【解决方案2】:

      在这种情况下,最好找到删除功能的提交,看看它可能被替换为什么。在这种情况下,HttpNotAcceptableOutputFormatter this commit 一起被删除以修复issue #4612

      更改内容协商算法,以便可以将其配置(通过 MvcOptions)始终尊重明确的 Accept 标头。

      它被替换为MvcOptions.ReturnHttpNotAcceptable,这是您在使用AddMvc 添加MVC 时配置的MvcOptions 上的设置。

      所以你的代码应该变成这样:

      services.AddMvc(options =>
      {
          options.ReturnHttpNotAcceptable = true;
      });
      

      【讨论】:

      • 你到底是怎么找到那个的?!
      • @Mardoxx 使用文件搜索(键盘快捷键:T)查看 RC2 分支和found the file。这告诉我文件最初的位置。然后我去了folder’s history on the dev branch并使用Gi​​tHub UI进行了“二进制搜索”以找到删除文件的提交。
      【解决方案3】:

      您将其添加到Startup 类中的ConfigureService 方法中。

      services.AddMvc(options =>
      {
          options.ReturnHttpNotAcceptable = true;
          // If you need to add support for XML
          // options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
      });
      

      【讨论】:

        【解决方案4】:

        以上答案都不适合我,终于成功了

        在 Startup.cs 的 ConfigureServices 中添加以下行

         public void ConfigureServices(IServiceCollection services)
         {
                services.AddMvcCore().AddJsonFormatters().AddApiExplorer();
         }
        

        【讨论】:

          猜你喜欢
          • 2018-05-31
          • 2019-12-15
          • 2019-04-30
          • 2018-07-22
          • 1970-01-01
          • 2019-05-05
          • 1970-01-01
          • 2019-11-17
          • 1970-01-01
          相关资源
          最近更新 更多