[英]Statuscode 406 (Not Acceptable) in ASP.NET Core
REST 服務應該提供內容協商。 這意味着客戶端發送一個 Accept 標頭,其中包含所需的響應內容類型。 如果服務不支持此媒體類型,則應以狀態代碼 406(不可接受)進行響應。
我嘗試將此行為映射到 ASP.NET Core。 如果 ASP.NET 核心無法識別 Accept 標頭中的媒體類型,則它會返回一個 JSON 文檔。 在以前版本的框架中,可以通過向配置添加特殊的輸出格式化程序來實現上述行為:
public void ConfigureServices(IServiceCollection services) {
services.AddMvc(options => {
options.OutputFormatters.Insert(0, new HttpNotAcceptableOutputFormatter());
});
}
不幸的是,在 RC1 之后, HttpNotAcceptableOutputFormatter
從 ASP.NET Core 框架中刪除。 在當前版本的框架中,這個類是否有替代品?
我以前有這個:
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();
}
在這種情況下,最好找到刪除功能的提交,看看它可能被替換為什么。 在這種情況下, HttpNotAcceptableOutputFormatter
已通過此提交刪除以修復問題 #4612 :
更改內容協商算法,以便可以將其配置(通過 MvcOptions)以始終遵守明確的 Accept 標頭。
它被替換的是MvcOptions.ReturnHttpNotAcceptable
,這是您在使用AddMvc
添加 MVC 時配置的MvcOptions
上的設置。
所以你的代碼應該變成這樣:
services.AddMvc(options =>
{
options.ReturnHttpNotAcceptable = true;
});
將此添加到Startup
類中的ConfigureService
方法。
services.AddMvc(options =>
{
options.ReturnHttpNotAcceptable = true;
// If you need to add support for XML
// options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
});
以上答案都不適合我,最后這奏效了
在 Startup.cs 的 ConfigureServices 中添加以下行
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore().AddJsonFormatters().AddApiExplorer();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.