asp.net core webapi处理Post请求中的request payload

request payload的Content-Type实际上是text/plain的,如果请求的 Content-Type 为 application/json,这将导致415 Unsupported Media Type HTTP error。

有两个解决方法

1使用  application/json

Content-Type采用application/json并确保 request payload是有效的json格式,比如

 
  
1  {
2     "cookie": "value"
3 } 

Then the action signature needs to accept an object with the same shape as the JSON object.

创建实体作为接收参数

1 public class CookieWrapper
2 {
3     public string Cookie { get; set; }
4 }
5 
6 ...
7 
8 public IActionResult GetRankings([FromBody] CookieWrapper c)

 

或者使用dynamic、Dictionary
1 public IActionResult GetRankings([FromBody] dynamic c) 
2 
3 public IActionResult GetRankings([FromBody] Dictionary<string, string> c) 

 

2使用 text/plain

客户端请求使用 Content-Type : text/plain,服务端添加TextPlainInputFormatter

 
  
 1 public class TextPlainInputFormatter : TextInputFormatter
 2 {
 3     public TextPlainInputFormatter()
 4     {
 5         SupportedMediaTypes.Add("text/plain");
 6         SupportedEncodings.Add(UTF8EncodingWithoutBOM);
 7         SupportedEncodings.Add(UTF16EncodingLittleEndian);
 8     }
 9 
10     protected override bool CanReadType(Type type)
11     {
12         return type == typeof(string);
13     }
14 
15     public override async Task<InputFormatterResult> ReadRequestBodyAsync(
16         InputFormatterContext context, 
17         Encoding encoding)
18     {
19         string data = null;
20         using (var streamReader = context.ReaderFactory(
21             context.HttpContext.Request.Body, 
22             encoding))
23         {
24             data = await streamReader.ReadToEndAsync();
25         }
26 
27         return InputFormatterResult.Success(data);
28     }
29 }
 
  
并在Startup.cs配置mvc
1 services.AddMvc(options =>
2 {
3     options.InputFormatters.Add(new TextPlainInputFormatter());
4 });
 
  

 

 

 翻译自https://stackoverflow.com/questions/41798814/asp-net-core-api-post-parameter-is-always-null

 

 

作者:B.it

 

技术收录网站:核心技术(http://www.coretn.cn)

本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

 

转载于:https://www.cnblogs.com/ImBit/p/8795805.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值