文章出處

ASP.NET Web API的內容協商(Content Negotiation)機制的理想情況是這樣的:客戶端在請求頭的Accept字段中指定什么樣的MIME類型,Web API服務端就返回對應的MIME類型的內容(響應頭的中Content-Type就是Accept中指定的MIME類型)。

而現實情況是,Web API服務端能返回什么MIME類型的響應類型取決于有沒有對應這個MIME類型的MediaTypeFormatter。ASP.NET Web API的默認實現中只提供了2種MediaTypeFormatter(我用的Web API版本是5.2)—— XmlMediaTypeFormatter與JsonMediaTypeFormatter。所以,在請求頭的Accept中除非指定為application/xml或者application/json,否則指定其它任何MIME,Web API都會返回application/json(這是默認的響應類型)。

今天就被這個現實情況折騰了半天,accept中指定text/plain,Web API總是返回json格式的數據。后來通過網絡抓包才發現這個問題。真搞不懂ASP.NET Web API為什么不默認實現一個PlainTextTypeFormatter。

被逼無奈,只能自己實現一個PlainTextTypeFormatter:

  • 繼承MediaTypeFormatter
  • 構造函數中添加MediaTypeHeaderValue("text/plain")
  • 重寫三個方法:CanReadType(), CanWriteType() 與 WriteToStreamAsync()

完整實現代碼如下:

public class PlainTextTypeFormatter : MediaTypeFormatter
{
    public PlainTextTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
    }

    public override bool CanReadType(Type type)
    {
        return false;
    }

    public override bool CanWriteType(Type type)
    {
        return type == typeof(string);
    }

    public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
    {
        using (var sw = new StreamWriter(writeStream))
        {
            await sw.WriteAsync(value.ToString());
        }              
    }
}

文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()