gpt4 book ai didi

asp.net-core - AspNetCore.SignalR 2.1和CORS

转载 作者:行者123 更新时间:2023-12-03 13:30:14 26 4
gpt4 key购买 nike

我正在将SignalR-Service迁移到新的AspNetCore.SignalR(2.1预览版),现在我遇到了CORS问题。我将永远不会从同一来源访问该服务,因此通常需要禁用CORS。

我有以下CORS政策

services.AddCors(
options => options.AddPolicy("AllowCors",
builder =>
{
builder
.AllowAnyOrigin()
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod();
})
);


(我的WebApi-Controller来自其他来源的调用在这些策略下工作正常)

使用SignalR for AspNetCore的旧预览包(AspNetCore.SignalR.Server),我没有任何问题,但是现在,我的测试客户端出现了一些http-405,这似乎与CORS有关。

SignalR是否可能需要额外的CORS配置,或者我需要允许其他设置吗?

编辑:
我创建了一个全新/干净的示例项目,没有任何特殊的中间件,以检查错误是否在此发生,并且确实如此。

WebApplication示例| startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WebApplication1.HUBs;

namespace WebApplication1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(
options => options.AddPolicy("AllowCors",
builder =>
{
builder
.AllowAnyOrigin()
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod();
})
);
services.AddMvc();
services.AddSignalR(options =>
{
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseCors("AllowCors");
app.UseMvc();
app.UseSignalR(routes =>
{
routes.MapHub<TestHub>("/test");
});
}
}
}


Winforms示例应用程序

        private HubConnection _hubConnection;
private void button1_Click(object sender, EventArgs e)
{
var connection = new HubConnectionBuilder().WithUrl("http://localhost:63771/test")
.WithConsoleLogger()
.WithTransport(Microsoft.AspNetCore.Sockets.TransportType.WebSockets)
.Build();
connection.StartAsync();
}


Winforms应用程序控制台示例输出

fail: Microsoft.AspNetCore.Sockets.Client.HttpConnection[8]
01/10/2018 15:25:45: Failed to start connection. Error getting negotiation response from 'http://localhost:63771/test'.
System.Net.Http.HttpRequestException: Response status code does not indicate success: 405 (Method Not Allowed).
bei System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
bei Microsoft.AspNetCore.Sockets.Client.HttpConnection.<Negotiate>d__42.MoveNext()

最佳答案

尝试像这样将app.UseSignalR()移动到app.UseMvc()的顶部

app.UseCors("AllowCors");
app.UseSignalR(routes =>
{
routes.MapHub<TestHub>("/test");
});
app.UseMvc();

关于asp.net-core - AspNetCore.SignalR 2.1和CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48185985/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com