由Nginx服务的Blazor WebAssembly App发出的此请求返回405方法不允许错误(POST):
研究发现,当Nginx用作反向代理时,有必要升级标头,但这不是我的情况。 Nginx在这里用作Web服务器。这是我的nginx.conf:
events {}
http {
include mime.types;
types {
application/wasm wasm;
}
server {
listen 80;
location / {
root /usr/share/nginx/html;
try_files $uri $uri/ /index.html =404;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, PATCH';
add_header 'Access-Control-Allow-Headers' 'Content-Type, X-Requested-With';
add_header 'Access-Control-Allow-Credentials' 'true';
}
}
}
这是我的后端api启动配置:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSignalR();
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed(host => true);
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chatHub");
endpoints.MapControllers();
});
}
我在这里想念什么?我是否必须映射nginx.conf中的特定位置“ / chatHub”才能以某种方式使用webSockets?
Ps .:我正在使用Docker容器(docker-compose)。
答案 0 :(得分:0)
尝试一下
...
server {
listen 80;
location /chatHub/ {
proxy_pass http://localhost:4000
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
location / {
root /usr/share/nginx/html;
try_files $uri $uri/ /index.html =404;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, PATCH';
add_header 'Access-Control-Allow-Headers' 'Content-Type, X-Requested-With';
add_header 'Access-Control-Allow-Credentials' 'true';
}
}
}
...
在docker-compose.yml上,确保您有
...
ports:
- "4000:4000"
...
答案 1 :(得分:0)
所以,毕竟问题不是Nginx。我正在向错误的端口发送请求。 Blazor应用程序不应通过Nginx,而应直接向后端请求。
我使用的是 NavigationManager 类来获取后端的URI,但我没有意识到默认情况下它指向前端的来源这给了我错误的URI。我正在关注tutorial,但由于没有使用Asp.net托管的Blazor Wasm版本,因此不得不进行一些修改。
问题是端点注册的顺序。 必须在控制器之后注册集线器,否则浏览器将抛出CORS错误。所以正确的是:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<ChatHub>("/chatHub");
});