asp net core 3 在发布后获取 BadRequest 对 POST 动作的正文内容响应

asp net core 3 Getting BadRequest response on POST action with body content after publish

我正在使用 asp.net 核心 3 构建一个网站,我将其托管在 Debian 9 服务器上,并使用 nginx 作为反向代理。我 运行 反对这个问题,即当我 运行 在本地 visual studio 应用程序时,我的 POST 请求确实有效,但是当我发布应用程序并将其上传到我的服务器,他们突然不工作了。

这是我用于测试的控制器:

public class TestController : Controller
{
    [HttpPost]
    public IActionResult Ping()
    {
        return Ok();
    }

    [HttpPost]
    public IActionResult Echo(string message)
    {
        return Ok(message);
    }

    [HttpPost]
    public IActionResult FormEcho([FromForm]string message)
    {
        return Ok(message);
    }
}

我正在使用 postman 来测试这些端点。

Ping:

Echo:

FormEcho:

根据这个测试,我认为 post 带有正文内容的请求在我的服务器上被拒绝了。我还从日志中注意到,对于服务器上 return 400 的请求,日志中没有任何内容,好像请求甚至没有到达我的应用程序。

为什么我的应用程序拒绝包含正文内容的 post 请求?


编辑:
这是我在 nginx 中的配置:

server {
    listen        443 ssl;
    listen        [::]:443 ssl;

    include snippets/self-signed.conf;
    include snippets/ssl-params.conf;

    server_name   51.38.35.10;

    error_log /var/log/nginx/error.log info;

    location / {
        proxy_pass         http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection 'upgrade';
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

server {
    listen        80;
    listen        [::]:80;

    server_name   51.38.35.10;

    return 302 https://$server_name$request_uri;
}

如果 ASP.NET 核心应用程序甚至不记录传入请求(而其他应用程序工作),那么它似乎实际上没有收到任何传入请求。在这种情况下,可能是您的反向代理配置没有让这些请求通过您的应用程序。

我通常通过 nginx 为 ASP.NET 核心应用程序使用以下配置:

location / {
    proxy_pass         http://localhost:5000;
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection keep-alive;
    proxy_set_header   Host $host;
    proxy_cache_bypass $http_upgrade;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto $scheme;
}

也就是recommendation from the official ASP.NET Core docs.

设置不同的 Connection header 值,特别是 Upgrade,似乎有点问题。我个人刚刚看到 Upgrade 与 WebSockets 的 HTTP Upgrade header 一起使用时的值。

所以调整nginx配置应该可以解决你的问题。

注意Connection keep-alive