簡體   English   中英

WebApi:將MediaTypeFormatter附加到控制器

[英]WebApi: Attach MediaTypeFormatter to Controller

我想從項目的全局格式化程序中刪除XmlFormatter 我正在為此:

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

但是同時我想擁有一個可以返回xml數據類型的控制器。 是否可以用特定屬性裝飾控制器或以某種方式將XmlFormatter附加到此控制器?

您需要創建一個自定義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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM