使用 Http.SYS 的 ASP.net Core Signalr 中的预检选项请求的 401 CORS 错误

问题描述

下面是我的启动文件

    public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {

        
        services.AddAuthentication(httpsysDefaults.AuthenticationScheme);
        services.AddCors(options =>
            options.AddPolicy("CorsPolicy",builder => builder.WithOrigins("http://localhost:8099").AllowAnyHeader().AllowAnyMethod().AllowCredentials()));
    }
    public void Configure(IApplicationBuilder app)
    {

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseCors("CorsPolicy");
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chathub",options =>
            {
                options.Transports = HttpTransportType.LongPolling;
            });

        });
    }

}

以下是我的 program.cs,当我执行 options.Authentication.AllowAnonymous = true 时一切正常,但是当我将其设为 false 时我收到 401 CORS 错误

   class Program
{
    static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }
    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                    .Usehttpsys()
                    .UseStartup<Startup>()
                    .Usehttpsys(options =>
                {
                    options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
                    options.Authentication.AllowAnonymous = true;
                    options.MaxAccepts = 25;                    //throttling of http.sys
                    options.MaxConnections = 25;
                    options.RequestQueueLimit = 25;
                });
}

以下是我在 localhost:8099 上运行的 Javascript 调用,我已经将其列入白名单

    <script>
jQuery.support.cors = true;
"use strict";

     var connection = new 
     signalR.HubConnectionBuilder().withUrl("http://localhost:5000/chatHub",{  transport: signalR.HttpTransportType.LongPolling },options =>
        {
        options.UseDefaultCredentials = true;
        }).build();
        
        start();
     
 async function start() {
try {
    await connection.start();
    console.log("SignalR Connected.");
    InvokeNow();
} catch (err) {
    console.log(err);
}
 };
 var message = "NewMessagesample"
function InvokeNow()
{
//Testing Callback functions - Calling Method in HUB
connection.invoke("SendMessage",message).catch(function (err) {
    return console.error(err.toString());
});
}

</script>

我的中心班

    [EnableCors("CorsPolicy")]
public class ChatHub : Hub
{
    public async Task SendMessage(string message)
    {
        await Clients.All.SendAsync("ReceiveMessage",message);
    }
}

匿名身份验证为 false 时的 CORS 错误

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)