我正在使用 asp.net core 3 构建一个网站,该网站托管在 Debian 9 服务器上,使用 nginx 作为反向代理。我正在解决这个问题,即当我在 Visual Studio 中本地运行应用程序时,我的 POST 请求确实可以工作,但是当我发布应用程序并将其上传到我的服务器时,它们突然不再工作了。
这是我用于测试的 Controller :
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
:从这个测试中,我认为在我的服务器上以某种方式拒绝了带有正文内容的发布请求。我还从日志中注意到,对于在服务器上返回 400 的请求,日志中没有任何内容,就好像该请求甚至没有到达我的应用程序一样。
为什么我的应用程序拒绝带有正文内容的发布请求?
编辑:
这是我在 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 Core 应用程序甚至没有记录传入的请求(而其他应用程序在工作),那么它似乎实际上没有收到任何传入的请求。在这种情况下,可能是您的反向代理配置没有让这些请求通过您的应用程序。
我通常通过 nginx 对 ASP.NET Core 应用程序使用以下配置:
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
与 HTTP 一起使用时的值 Upgrade
WebSocket 的 header 。所以调整nginx配置应该可以解决你的问题。
请注意
Connection keep-alive
关于nginx - asp net core 3 在发布后获取带有正文内容的 POST 操作的 BadRequest 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59234780/