SignalR在通知/协商请求上抛出405错误

4

我像这样使用Angular连接到服务器:

    this._hubConnection = new signalR.HubConnectionBuilder()
  .withUrl(location.protocol + '//localhost:5000/notify')
  .configureLogging(signalR.LogLevel.Information)
  .build();

代码或主机没有问题,请求是有效的。

但是库会发起额外的调用:

http://localhost:5000/notify/negotiate

然后我得到了这个错误:

HTTP ERROR 405

客户端显示的完整错误信息如下:

Failed to load http://localhost:5000/notify/negotiate: Response to 

preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

除了上述请求外,我在该网站中没有跨域问题。
我已经在startup.cs中进行了配置。
     app.UseCors(builder =>
              builder.WithOrigins("http://localhost:4200").AllowAnyMethod
 ().AllowAnyHeader().AllowAnyOrigin());

这段代码适用于整个网站。

为什么其他请求都能正常工作,突然出现跨域错误?


UseCors 调用中,您有 WithOrigins(...)AllowAnyOrigin()。尝试移除 AllowAnyOrigin() 调用,看看是否可以解决问题? - Simply Ged
1个回答

0
我可以建议您直接配置 web.config 文件,将以下代码行添加到您的 Web 应用程序中(它适用于 IIS,但不确定是否适用于 IIS Express):
<system.webServer>
   <httpProtocol>
      <customHeaders>
         <add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
         <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS,PUT,DELETE,PATCH" />
         <add name="Access-Control-Allow-Headers" value="Content-Type, X-Requested-With" />
         <add name="Access-Control-Allow-Credentials" value="true" />
      </customHeaders>
   </httpProtocol>
</system.webServer>

我在 .net core 中找不到这个。 - Johan Van Wambeke
@JohanVanWambeke 我提供的解决方案仅适用于 .NET Standard,不适用于 .NET Core。 - D. Pesc.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接