WebApi:将 MediaTypeFormatter 附加到控制器

WebApi: Attach MediaTypeFormatter to Controller

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

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

但同时我想要一个可以 return xml 数据类型的控制器。是否可以用特定属性装饰我的控制器或以某种方式专门将 XmlFormatter 附加到该控制器?

您需要创建自定义 System.Net.Http.Formatting.IContentNegotiator class 并将选定的格式化程序检查到 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());