WEB API 各请求类型对接方式
- 接入 text/plain
- 返回 application/json
接入 text/plain
ASP.NET Web API的内容协商(Content Negotiation)机制的理想情况是这样的:客户端在请求头的Accept字段中指定什么样的MIME类型(响应头的中Content-Type),Web API服务端就返回对应的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(这是默认的响应类型)。
如果需要接入text/plain时,需要自己实现PlainTextTypeFormatter。步骤如下:
- 请求头加入text/plain标识
Content-type:text/plain
- 后端新增一个类,类名为PlainTextTypeFormatter
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
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();
}
}
}
- 在WebApiConfig.cs类中加入以下代码,将该类注册至forrmator 中。
config.Formatters.Add(new PlainTextTypeFormatter());
- 控制器通过以下方式接收并且处理
[Route("api/ct/test1")]
[HttpPost]
public HttpResponseMessage test1([FromBody] string request)
{
try
{
LogHelper.Write("test1:" + request);
...
返回 application/json
- 控制器返回值修改为 HttpResponseMessage
- 将返回信息转换为 HttpResponseMessage 对象
[Route("api/ct/test1")]
[HttpPost]
public HttpResponseMessage test1([FromBody] string request)
{
LogHelper.Write("test1:" + request);
...
...
string str = "{\"resultCode\":\"0000\",\"resultMessage\":\"success\"}";
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
更多推荐
WEB API 各Content-Type对接方式
发布评论