【发布时间】:2019-12-27 08:26:17
【问题描述】:
我在我的 Ubuntu 18.04 服务器上发布了一个 WEB API 应用程序 (.Net Core 3.1),它在 NGINX 后面运行。 我的 GET 方法在本地机器和远程服务器上都有效。但是我的 POST 方法只能在我的本地机器上工作,但不能在远程服务器上工作,尽管我尝试了很多东西。我从远程服务器收到 400(错误请求)错误。我无法弄清楚它背后的原因是什么。 这是我的代码:
public class MyCls
{
public string MyString { get; set; }
public int MyInt { get; set; }
}
[Route("[controller]")]
[ApiController]
public class NewController : ControllerBase
{
[HttpGet("MyGetRoute")]
public string Method1()
{
return "Hello from server.";
}
[HttpPost("MyPostRoute")]
public MyCls Method2(MyCls str)
{
var options = new JsonSerializerOptions
{
// PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
str.MyString = str.MyString + " John";
str.MyInt = str.MyInt + 2;
return str;
}
[HttpPost("MyPostRoute2")]
public string Method3(MyCls str2)
{
return str2.MyString;
}
}
这是我在 html 页面中的代码:
function postIt() {
axios.post('New/MyPostRoute', {
MyString: 'Fred',
MyInt: 4,
}
).then(function (response) {
document.getElementById("p1").innerHTML = response.data.myString + " " + response.data.myInt;
console.log(response.Text);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
});
}
function postIt2() {
axios.post('New/MyPostRoute2', {
MyString: 'Fred',
}
).then(function (response) {
document.getElementById("p1").innerHTML = response.data;
console.log(response.Text);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
});
}
function getIt() {
axios.get('New/MyGetRoute')
.then(function (response) {
document.getElementById("p1").innerHTML = response.data;
console.log(response.Text);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
});
}
这是我的 NGINX 配置:
server {
listen 80;
listen [::]:80;
index index.html home.html
server_name dotnet.xxxxxx.com www.dotnet.xxxxxx.com;
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 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;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/xxxxxx.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/xxxxxx.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = dotnet.xxxxxx.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
【问题讨论】:
-
既然你的问题是在把你的web应用放在 nginx之后出现的,你能不能也分享一下你的nginx配置?
-
@poke 我添加了 NGINX 配置。
-
我认为你应该看看你的 Nginx 日志。添加到 /etc/nginx/nginx.conf 的第一行:error_log /var/log/nginx/error.log debug;之后重新启动 nginx,你应该有一些日志条目。
标签: c# asp.net-core nginx .net-core asp.net-core-webapi