当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net core webapi处理Post请求中的request payload

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

2018年04月13日  | 移动技术网IT编程  | 我要评论

丁俊晖威尔士公开赛,网上结婚,广西电视网

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网