c# - Asp.net core 2.0 POST 端点在没有 json 有效负载的情况下工作,但在使用 json 有效负载时失败(400 错误请求)

标签 c# json asp.net-core .net-core

我的 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 因为 JObjectnull 但这仍然是预期的行为。

但是,当像这样调用 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,将不起作用。请指定包含 urlalt 属性的 POCO 类。

关于c# - Asp.net core 2.0 POST 端点在没有 json 有效负载的情况下工作,但在使用 json 有效负载时失败(400 错误请求),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49736359/

相关文章:

c# - 调用 BeginSaveChanges(null, null) 来执行“即发即忘”异步 DataContext 调用是否安全?

javascript - 如何改进 JSON 数据的显示

c# - Asp.Net Core - Identity SignInManager - 如何使用附加条件登录以便用户登录(例如 : ClientId, 用户名和密码))

json - 查找网络上的所有 Yammer 组(也许使用 API)?

javascript - 如何在 Perl 中打开 javascript 对象?

postgresql - 应用程序无法在 docker 中运行,无法加载文件或程序集 'System.Runtime.CompilerServices.Unsafe

c# - 使用 Azure 地理冗余 (RA-GRS) 表存储时,如何更新 ASP.NET Core 中的 TableServiceClient 以指向辅助区域?

c# - 内存消耗 .Net 应用程序(Azure 网站)

c# - 使用 EF6 的类构造函数中的 List<xx> 和 HashSet<xx> 有什么区别?

c# - 相当于 Promise.then() 的任务是什么?