ASP.NET Core API POST参数始终为null

我看过以下内容:

  • Asp.net Core Post参数始终为null
  • asp.net webapi 2 post参数始终为null
  • web-api POST正文对象始终为null
  • Web Api参数始终为null

我的终点:

[HttpPost] [Route("/getter/validatecookie")] public async Task GetRankings([FromBody] string cookie) { int world = 5; ApiGetter getter = new ApiGetter(_config, cookie); if (!await IsValidCookie(getter, world)) { return BadRequest("Invalid CotG Session"); } HttpContext.Session.SetString("cotgCookie", cookie); return Ok(); } 

我的请求:

 $http.post(ENDPOINTS["Validate Cookie"], cookie , {'Content-Type': 'application/json'}); 

其中cookie是我从用户输入发送的字符串。

请求使用适当的数据发布到端点。 但是,我的字符串始终为null。 我试过删除[FromBody]标签,并在发布的数据前加上一个=没有运气。 我还尝试使用上述所有组合添加和删除不同的内容类型。

我正在做这个具体行动的原因很长,对这个问题无关紧要。

无论我做什么,为什么我的参数总是为空?

编辑:我也尝试过使用{cookie: cookie}

Edit2 :请求:

 Request URL:http://localhost:54093/getter/validatecookie Request Method:POST Status Code:400 Bad Request Remote Address:[::1]:54093 

响应标题

 Content-Type:text/plain; charset=utf-8 Date:Mon, 23 Jan 2017 03:12:54 GMT Server:Kestrel Transfer-Encoding:chunked X-Powered-By:ASP.NET X-SourceFiles:=?UTF-8?B?QzpcVXNlcnNcRG91Z2xhc2cxNGJcRG9jdW1lbnRzXFByb2dyYW1taW5nXENvdEdcQ290RyBBcHBcc3JjXENvdEdcZ2V0dGVyXHZhbGlkYXRlY29va2ll?= 

请求标题

 POST /getter/validatecookie HTTP/1.1 Host: localhost:54093 Connection: keep-alive Content-Length: 221 Accept: application/json, text/plain, */* Origin: http://localhost:54093 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 Content-Type: application/json;charset=UTF-8 Referer: http://localhost:54093/ Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.8 

请求有效负载

 =sec_session_id=[redacted]; _ga=[redacted]; AWSELB=[redacted] 

问题是Content-Typeapplication/json ,而请求有效负载实际上是text/plain 。 这将导致415 Unsupported Media Type HTTP错误。

您至少有两个选项可以对齐Content-Type和实际内容。

使用application / json

Content-Type保留为application/json ,并确保请求有效内容是有效的JSON。 例如,将您的请求有效负载设为:

 { "cookie": "=sec_session_id=[redacted]; _ga=[redacted]; AWSELB=[redacted]" } 

然后,操作签名需要接受与JSON对象具有相同形状的对象。

 public class CookieWrapper { public string Cookie { get; set; } } 

而不是CookieWrapper类,或者您可以接受动态或Dictionary并在端点中像cookie["cookie"]一样访问它

 public IActionResult GetRankings([FromBody] CookieWrapper cookie) public IActionResult GetRankings([FromBody] dynamic cookie) public IActionResult GetRankings([FromBody] Dictionary cookie) 

使用text / plain

另一种方法是将Content-Type更改为text/plain ,并将纯文本输入格式化程序添加到项目中。 为此,请创建以下类。

 public class TextPlainInputFormatter : TextInputFormatter { public TextPlainInputFormatter() { SupportedMediaTypes.Add("text/plain"); SupportedEncodings.Add(UTF8EncodingWithoutBOM); SupportedEncodings.Add(UTF16EncodingLittleEndian); } protected override bool CanReadType(Type type) { return type == typeof(string); } public override async Task ReadRequestBodyAsync( InputFormatterContext context, Encoding encoding) { string data = null; using (var streamReader = context.ReaderFactory( context.HttpContext.Request.Body, encoding)) { data = await streamReader.ReadToEndAsync(); } return InputFormatterResult.Success(data); } } 

并配置Mvc使用它。

 services.AddMvc(options => { options.InputFormatters.Add(new TextPlainInputFormatter()); }); 

也可以看看

https://github.com/aspnet/Mvc/issues/5137

Shaun Luttin的回答是有效的,但它错过了一条重要的信息。 无法识别字符串的原因是因为它不是JSON字符串。

做这个;

 var payload=JSON.stringify("=sec_session_id=[redacted]; _ga=[redacted]; AWSELB=[redacted]"); 

然后你可以按原样离开控制器;

 $.ajax({ url: http://localhost:54093/getter/validatecookie, type: 'POST', contentType: 'application/json', data: payload }); 

令我尴尬的是这让我弄清楚了多长时间。 我真的希望它可以帮助别人!

你只需要将主体放在引号中,使其代表一个string 。 您还需要将请求类型保留为application/json 。 那样媒体类型格式化器就会弄明白:

 "=sec_session_id=[redacted]; _ga=[redacted]; AWSELB=[redacted]" 

应该做的伎俩。

可笑的是,在dot net core中你不能只使用“frombody string parameter”。 你应该只为一个字符串参数创建一个模型类。

 public async Task GetRankings([FromBody] string cookie) 

=>

 //1. make a model. MyCookie.cs class MyCookie{ public string Cookie { get; set; } } //2. edit your parameter public async Task GetRankings([FromBody] MyCookie cookie)