简体   繁体   中英

WebApi: Attach MediaTypeFormatter to Controller

I would like to remove XmlFormatter from global formatters in my project. 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. Is it possible to decorate my controller with specific attribute or somehow attach XmlFormatter specifically to this controller?

You need to create a custom System.Net.Http.Formatting.IContentNegotiator class and check the selected formatter into the Negotiate method.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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