webapi 支持 text/plain 請求

今天遇到一個需求,請求以HTTPS + XML 訪問個人API ,普通的webapi 是不支持這個請求的,故作如下代碼進行支持web

 

新增一個類,類名爲PlainTextTypeFormatterapi

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

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

    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());
        }
    }

    public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream,
        HttpContent content, IFormatterLogger formatterLogger)
    {
        using (var sr = new StreamReader(readStream))
        {
            return await sr.ReadToEndAsync();
        }
    }
}

 

而後在註冊該類到forrmator 中去,(在webapiconfig 中加入如下代碼)async

config.Formatters.Add(new PlainTextTypeFormatter());

 

而後在請求時別忘記在頭部加上,不然請求不能被處理ide

Content-type:text/plain

 

如下是在fiddler 中請求結果如圖spa

 

相關文章
相關標籤/搜索