WebApi:将MediaTypeFormatter附加到Controller

时间:2015-02-06 14:35:09

标签: asp.net-web-api asp.net-web-api2

我想从项目中的全局格式化程序中删除XmlFormatter。我这样做是为了它:

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

但同时我希望有一个控制器可以返回xml数据类型。是否可以使用特定属性装饰我的控制器或以某种方式将XmlFormatter专门附加到此控制器?

1 个答案:

答案 0 :(得分:2)

您需要创建自定义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);
    }
}

然后将您的IContentNegotiator实施服务替换为HttpConfiguration对象

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