如何使用格式化程序?

时间:2017-12-22 04:02:45

标签: asp.net-core-2.0 asp.net-core-webapi formatter

我在尝试通过在网址末尾添加.xml.json来创建XML和JSON的输出时,遵循此示例https://tahirnaushad.com/2017/09/03/formatters-in-asp-net-core-2-0-web-api/

这个例子只讨论xml,但我不能这样做。以下是我的代码。

[Route("api/check")]
public class MyController : Controller
{
    [HttpGet]
    [HttpGet("/check1.{format}"), FormatFilter]
    public string Get()
    {
        return "testing check1";
    }
...
}

访问:

http://localhost/api/check/

以HTML格式返回以下内容:

  

测试check1

http://localhost/api/check/check1.xml显示白页。

我在startup.cs中有以下内容:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.ReturnHttpNotAcceptable = true;
        options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
        options.InputFormatters.Add(new XmlSerializerInputFormatter());
        options.OutputFormatters.Add(new XmlSerializerOutputFormatter());

        options.FormatterMappings.SetMediaTypeMappingForFormat(
                                     "xml", "application/xml");
    });
}

关于我做错的任何想法?

0 个答案:

没有答案