我的 asp.net core 2.0 应用程序中有以下端点:
[HttpPost("postself")]
public IActionResult post([FromBody]JObject email)
{
try
{
var service = new EmailService();
var emailHtml = service.GenerateEmail(email.ToString(), false);
return Json(new { Email = emailHtml });
}
catch
{
return Json(new { Email = "error" });
}
}
像这样调用 API 时:
curl -X POST \
http://myapp/api/v1/emails/postself \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-H 'postman-token: 85c9bbe7-2112-0746-5f41-8dc01b52ab59'
端点被命中并在 return Jason(new { Email = "error"});
处返回,这样就可以了。它返回 error
因为 JObject
是 null
但这仍然是预期的行为。
但是,当像这样调用 API 时(使用 JSON 负载):
curl -X POST \
http://myapp/api/v1/emails/postself \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-H 'postman-token: a80c85de-8939-01d8-4a5d-c2108bf1491d' \
-d '{
"body": [
{
"image": {
"url": "mailing_logo_slice.png",
"alt": "This is my logo"
}
}
]
}'
...我的应用返回 400 Bad request
。
此外,请求在开发中有效,但在生产中仅返回 400
。
有什么想法吗?
=========
更新代码:
[HttpPost("postself")]
public IActionResult PostSameDomain([FromBody]string email)
{
try
{
var service = new EmailGenerationService();
var emailHtml = service.GenerateEmailFromJson(email, false);
return Json(new { Email = emailHtml });
}
catch
{
return Json(new { Email = "error" });
}
}
[HttpPost("test")]
public IActionResult PostSameDomain([FromBody]EmailViewModel email)
{
try
{
var service = new EmailGenerationService();
var emailHtml = service.GenerateEmailFromJson(email.Raw, false);
return Json(new { Email = emailHtml });
}
catch
{
return Json(new { Email = "error" });
}
}
最佳答案
JObject
特定于 Newtonsoft.Json,将不起作用。请指定包含 url
和 alt
属性的 POCO 类。
关于c# - Asp.net core 2.0 POST 端点在没有 json 有效负载的情况下工作,但在使用 json 有效负载时失败(400 错误请求),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49736359/