Llo*_*oyd 5 c# asp.net-core asp.net-core-webapi asp.net-core-2.0
目前我对基本的ASP.NET Core 2 API项目和内容协商以及返回JSON以外的其他内容感到非常困惑.
我之前在1.1项目中有过这个工作但不是在2.我基本上想要根据请求类型返回JSON或XML.
作为该要求的一部分,我设置了XML格式化器,如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.ReturnHttpNotAcceptable = true;
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});
}
Run Code Online (Sandbox Code Playgroud)
我也可以使用AddXmlSerializerFormatters()相同的差异(和试过).这是我在无数个例子中看到的并且之前已经完成的方式.
我有一个控制器和单个动作,基本上看起来像:
[Route("api/[controller]")]
public class DefaultController : Controller
{
[HttpGet]
[Route("")]
public IActionResult Index()
{
return Ok(new
{
success = true
});
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当我跑步时,我在Postman中得到了这个:
{"success": true}
Run Code Online (Sandbox Code Playgroud)
所以它对JSON起作用(或者至少是默认值).
然后,如果我请求使用标头,Accept: application/xml我现在得到406的HTTP错误.
如果我起飞options.ReturnHttpNotAcceptable = true;,它将返回JSON,无论如何.
我错过了什么?我坐在这上面摸不着头脑.据我所知,我已经注册了一个可接受的内容格式化程序.
| 归档时间: |
|
| 查看次数: |
1670 次 |
| 最近记录: |