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 中请求结果如图
作者:ChenHuzi