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)

本文版權歸作者,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM