webapi 支持 text/plain 請求


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

 

新增一個類,類名為PlainTextTypeFormatter

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 中加入以下代碼)

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

 

然后在請求時別忘記在頭部加上,否則請求不能被處理

Content-type:text/plain

 

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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM