ASP.NET Core API POST 参数始终为空 [英] ASP.NET Core API POST parameter is always null
问题描述
我已阅读以下内容:
我的端点:
[HttpPost]
[Route("/getter/validatecookie")]
public async Task<IActionResult> 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
是我从用户输入发送的字符串.
Where cookie
is the a string I am sending from the user input.
请求发布到具有适当数据的端点.但是,我的字符串始终为空.我已经尝试删除 [FromBody]
标签,以及在发布的数据前添加一个 =
,但没有成功.我还尝试使用上述所有组合添加和删除不同的内容类型.
The request posts to the endpoint with the appropriate data. However, my string is always null. I have tried removing the [FromBody]
tag, as well as adding a =
in front of the posted data with no luck. I have also tried adding and removing different content types with all combinations of the above.
我做这个具体操作的原因很长,对于这个问题无关紧要.
The reason why I am doing this specific action is long and does not matter for this question.
为什么无论我做什么,我的参数总是为空?
Why is my parameter always null no matter what I seem to do?
我也尝试过使用 {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-Type
是application/json
,而请求payload实际上是文本/纯文本
.这将导致 415 Unsupported Media Type HTTP 错误.
The problem is that the Content-Type
is application/json
, whereas the request payload is actually text/plain
. That will cause a 415 Unsupported Media Type HTTP error.
您至少有两个选项可以对齐 Content-Type
和实际内容.
You have at least two options to align then Content-Type
and the actual content.
保持 Content-Type
为 application/json
并确保请求有效负载是有效的 JSON.例如,使您的请求有效负载为:
Keep the Content-Type
as application/json
and make sure the request payload is valid JSON. For instance, make your request payload this:
{
"cookie": "=sec_session_id=[redacted]; _ga=[redacted]; AWSELB=[redacted]"
}
然后动作签名需要接受一个与JSON对象形状相同的对象.
Then the action signature needs to accept an object with the same shape as the JSON object.
public class CookieWrapper
{
public string Cookie { get; set; }
}
代替 CookieWrapper
类,或者您可以接受动态或 Dictionary
并像 cookie["cookie"] 一样访问它
在端点
Instead of the CookieWrapper
class, or you can accept dynamic, or a Dictionary<string, string>
and access it like cookie["cookie"]
in the endpoint
public IActionResult GetRankings([FromBody] CookieWrapper cookie)
public IActionResult GetRankings([FromBody] dynamic cookie)
public IActionResult GetRankings([FromBody] Dictionary<string, string> cookie)
使用文本/纯文本
另一种选择是将您的 Content-Type
更改为 text/plain
并向您的项目添加纯文本输入格式化程序.为此,请创建以下类.
Use text/plain
The other alternative is to change your Content-Type
to text/plain
and to add a plain text input formatter to your project. To do that, create the following class.
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<InputFormatterResult> 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 以使用它.
And configure Mvc to use it.
services.AddMvc(options =>
{
options.InputFormatters.Add(new TextPlainInputFormatter());
});
另见
https://github.com/aspnet/Mvc/issues/5137
这篇关于ASP.NET Core API POST 参数始终为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!