Nginx托管Signalr Blazor Wasm应用程序:不允许使用405方法



Nginx服务的Blazor WebAssembly应用程序的此请求返回405方法不允许错误(POST(:

http://localhost:4000/chatHub/negotiate?negotiateVersion=1

研究发现,当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(。

试试这个

...
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';
}
}
}
...

在码头上。yml确保你有

...
ports:
- "4000:4000"
...

所以,问题根本不是Nginx。我向错误的端口发送了一个请求。Blazor应用程序不应该通过Nginx,而是直接向后端请求。

我使用NavigationManager类将URI获取到后端,但我没有意识到它默认指向前端的原点,这给了我错误的URI。我遵循了教程,但我不得不做一些修改,因为我没有使用Blazor Wasm的Asp.net托管版本。

但问题在于端点注册的顺序集线器必须在控制器之后注册,否则浏览器将抛出CORS错误。因此正确的做法是:

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<ChatHub>("/chatHub");
});

相关内容

  • 没有找到相关文章

最新更新