今天在web api中遇到了这样一个问题,虽然api的参数类型是string,但只能接收post body中json格式的string,不能接收原始string。

web api是这样定义的:

public async Task<HttpResponseMessage> Post(string blogApp, int postId, [FromBody] string body)
{
}

以json格式向web api进行post能成功:

var response = await _httpClient.PostAsJsonAsync(
$"api/blogs/{blogApp}/posts/{postId}/comments",
body);

但以纯文本格式(content-type为text/plain)post,body的值却为空。

var response = await _httpClient.PostAsync(
$"api/blogs/{blogApp}/posts/{postId}/comments",
new StringContent(body)
);

研究后发现,这是由于对于content-type为text/plain的post请求,asp.net web api没有提供对应的MediaTypeFormatter,asp.net web api默认只提供了JsonMediaTypeFormatter与XmlMediaTypeFormatter。

所以要解决这个问题,需要自己实现一个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();
}
}
}

在上面的实现代码中,解决本文中的问题只需实现CanReadType()与ReadFromStreamAsync()。CanWriteType()与ReadFromStreamAsync()的实现是为了解决另外一个问题,详见:让ASP.NET Web API支持text/plain内容协商 。

让ASP.NET Web API支持POST纯文本格式(text/plain)的数据的更多相关文章

  1. 通过扩展让ASP.NET Web API支持JSONP

    同源策略(Same Origin Policy)的存在导致了"源"自A的脚本只能操作"同源"页面的DOM,"跨源"操作来源于B的页面将会被拒 ...

  2. 通过扩展让ASP.NET Web API支持W3C的CORS规范

    让ASP.NET Web API支持JSONP和W3C的CORS规范是解决"跨域资源共享"的两种途径,在<通过扩展让ASP.NET Web API支持JSONP>中我们 ...

  3. 通过微软的cors类库,让ASP.NET Web API 支持 CORS

    前言:因为公司项目需要搭建一个Web API 的后端,用来传输一些数据以及文件,之前有听过Web API的相关说明,但是真正实现的时候,感觉还是需要挺多知识的,正好今天有空,整理一下这周关于解决COR ...

  4. 通过扩展让ASP.NET Web API支持W3C的CORS规范(转载)

    转载地址:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-04.html CORS(Cross-Origin Resource Shari ...

  5. 让ASP.NET Web API支持$format参数的方法

    在不使用OData的情况下,也可以让ASP.NET Web API支持$format参数,只要在WebApiConfig里添加如下三行红色粗体代码即可: using System; using Sys ...

  6. (转)通过扩展让ASP.NET Web API支持JSONP

    原文地址:http://www.cnblogs.com/artech/p/3460544.html 同源策略(Same Origin Policy)的存在导致了“源”自A的脚本只能操作“同源”页面的D ...

  7. [转]让ASP.NET Web API支持$format参数的方法

    本文转自:http://www.cnblogs.com/liuzhendong/p/4228592.html 在不使用OData的情况下,也可以让ASP.NET Web API支持$format参数, ...

  8. 【ASP.NET Web API教程】5.3 发送HTML表单数据:文件上传与多部分MIME

    原文:[ASP.NET Web API教程]5.3 发送HTML表单数据:文件上传与多部分MIME 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面 ...

  9. 【ASP.NET Web API教程】5.2 发送HTML表单数据:URL编码的表单数据

    原文:[ASP.NET Web API教程]5.2 发送HTML表单数据:URL编码的表单数据 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内 ...

随机推荐

  1. WEB服务器、应用程序服务器、HTTP服务器区别

    很清晰的解释了WEB服务器.应用程序服务器.HTTP服务器区别 转载自 http://www.cnblogs.com/zhaoyl/archive/2012/10/10/2718575.html WE ...

  2. Linux命令之reset - 终端屏幕混乱的终结者

    用途说明 reset命令是用来重新初始化终端的(terminal initialization).在有些情况,终端显示会混乱无比,比如不小心显示了一个二进制文件,以前我在不知道reset命令时,只好将 ...

  3. python生成器和迭代器

    生成器:具有生成能力的对象 迭代器:具有取值功能的对象 def func(): yield 1 yield 2 yield 3 ret = func() #func()函数体称为生成器 r=ret._ ...

  4. memcpy code

    memcpy #include <stddef.h> //#include <stdint.h> //uintptr_t is quoted.#include "st ...

  5. Multipart to single part feature

    Multipart to single part feature Explode Link: http://edndoc.esri.com/arcobjects/8.3/?URL=/arcobject ...

  6. 关于Nios II的启动分析(转载)

    原文地址:http://hi.baidu.com/goatdai/item/cc33671545d89243e75e06ad 常用到的存储器包括SDRMA.SRAM.FLASH.Onchip_memo ...

  7. Linux(centos)系统各个目录的作用详解

    Linux(centos)系统各个目录的作用详解 文件系统的类型 LINUX有四种基本文件系统类型:普通文件.目录文件.连接文件和特殊文件,可用file命令来识别. 普通文件:如文本文件.C语言元代码 ...

  8. anomaly detection algorithm

    anomaly detection algorithm 以上就是异常监测算法流程

  9. Mahout源码分析之 -- QR矩阵分解

    一.算法原理 请参考我在大学时写的<QR方法求矩阵全部特征值>,其包含原理.实例及C语言实现:http://www.docin.com/p-114587383.html 二.源码分析 这里 ...

  10. php 万能加密

    function fue($hash,$times) { // Execute the encryption(s) as many times as the user wants for($i=$ti ...