WEB API 各Content-Type对接方式

WEB API 各请求类型对接方式

接入 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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值