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 中。
- 控制器通過以下方式接收并且處理
[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;
}