【问题标题】:How do I change the default response content type in an ASP.NET Core API?如何更改 ASP.NET Core API 中的默认响应内容类型?
【发布时间】:2020-05-10 22:47:48
【问题描述】:

我正在将旧版 API 重新实现为 ASP.NET Core web API。我已经实现了content negotiation,它运行良好——所有操作都支持JSONXML 响应格式,基于请求中的Accept header。我的问题是,如果没有指定 Accept 标头,原始 API 默认为 XML,而我的 ASP.NET Core API 默认为 JSON。没有 Accept 标头时如何设置默认响应内容类型 XML?

【问题讨论】:

标签: asp.net-core-webapi


【解决方案1】:

可以在Startup中配置

public void ConfigureServices(IServiceCollection services)
    {

        services.AddMvc(options => {
            options.OutputFormatters.Insert(0, new XmlDataContractSerializerOutputFormatter());
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

或者只是在你的控制器中使用属性Produces

[Produces("application/xml")]
public class MyController()
{
 ...
}

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 2018-09-25
    • 1970-01-01
    • 2019-12-18
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    相关资源
    最近更新 更多