WEB API 各Content-Type对接方式

编程知识 更新时间:2023-04-05 05:57:09

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。步骤如下:

  1. 请求头加入text/plain标识
Content-type:text/plain
  1. 后端新增一个类,类名为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();
        }
    }
}
  1. 在WebApiConfig.cs类中加入以下代码,将该类注册至forrmator 中。
config.Formatters.Add(new PlainTextTypeFormatter());
  1. 控制器通过以下方式接收并且处理
[Route("api/ct/test1")]
[HttpPost]
public HttpResponseMessage test1([FromBody] string request)
{
	try
	{
	    LogHelper.Write("test1:" + request);
	    ...

返回 application/json

  1. 控制器返回值修改为 HttpResponseMessage
  2. 将返回信息转换为 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对接方式

本文发布于:2023-04-05 05:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/dccc333466f9a34a3026d265a9b85444.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方式   API   WEB   Type   Content

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 45135文章数
  • 14阅读数
  • 0评论数