简体   繁体   English

WebApi:将MediaTypeFormatter附加到控制器

[英]WebApi: Attach MediaTypeFormatter to Controller

I would like to remove XmlFormatter from global formatters in my project. 我想从项目的全局格式化程序中删除XmlFormatter I am doing this for it: 我正在为此:

var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter)

But in the same time I would like to have one controller which can return xml data type. 但是同时我想拥有一个可以返回xml数据类型的控制器。 Is it possible to decorate my controller with specific attribute or somehow attach XmlFormatter specifically to this controller? 是否可以用特定属性装饰控制器或以某种方式将XmlFormatter附加到此控制器?

You need to create a custom System.Net.Http.Formatting.IContentNegotiator class and check the selected formatter into the Negotiate method. 您需要创建一个自定义System.Net.Http.Formatting.IContentNegotiator类,然后将选定的格式化程序签入Negotiate方法中。

public class ApplicationContentNegotiator : IContentNegotiator
{
    private readonly JsonMediaTypeFormatter _jsonFormatter;
    private readonly MediaTypeHeaderValue _jsonMediaType;

    private readonly XmlMediaTypeFormatter _xmlFormatter;
    private readonly MediaTypeHeaderValue _xmlMediaType;

    public static IContentNegotiator Create()
    {
        return new ApplicationContentNegotiator();
    }

    private ApplicationContentNegotiator()
    {
        _jsonFormatter = new JsonMediaTypeFormatter();
        _jsonMediaType = MediaTypeHeaderValue.Parse("application/json");

        _xmlFormatter = new XmlMediaTypeFormatter();
        _xmlMediaType = MediaTypeHeaderValue.Parse("application/xml");
    }

    public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
    {
        var controller = new DefaultHttpControllerSelector(request.GetConfiguration()).SelectController(request);
        if (controller.ControllerName == "MyController")
            return new ContentNegotiationResult(_xmlFormatter, _xmlMediaType);

        return new ContentNegotiationResult(_jsonFormatter, _jsonMediaType);
    }
}

And then replacing your IContentNegotiator implementation service into HttpConfiguration object 然后将您的IContentNegotiator实现服务替换为HttpConfiguration对象

GlobalConfiguration.Configuration.Services.Replace(typeof(IContentNegotiator), ApplicationContentNegotiator.Create());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM