【问题标题】:CORS error when using SignalR Core in angular app在角度应用程序中使用 SignalR Core 时出现 CORS 错误
【发布时间】:2019-12-07 00:07:35
【问题描述】:

在 CORS 配置中,我允许使用 OPTIONS 方法,但是当我发送请求时,会抛出错误

选项http://x.x.x.x:port/function 405(方法不允许)

我在 Startup.cs 中的 ConfigureServices 方法中的 CORS 策略如下:

services.AddCors(options =>
{
    options.AddPolicy("AllowAny", x =>
  {
    x.AllowAnyOrigin()
     .AllowAnyHeader()
     .WithMethods("POST", "OPTIONS");
  });
});

它的用法如下:

app.UseCors("AllowAny");

中心代码:

public async Task SendMessage(string user, string message) {
   string outputMessage = SensorsControl.controlSensors(message.ToString()); 
   await Clients.All.SendAsync("ReceiveMessage", user, outputMessage);
}

角度的SignalR代码:

this._hubConnection = new HubConnection('http://x.x.x.x:port/function'); 
this._hubConnection.start() 
                   .then(() => console.log('Connection started!')) 
                   .catch(err => console.log('Error while establishing connection')); 
this._hubConnection.on('ReceiveMessage', (user: string, outputMessage: string) => 
{ 
  const text = ${user}: ${outputMessage}; this.messages.push(text); 
}); 

【问题讨论】:

  • 你能显示你的信号器代码和你的集线器代码吗?
  • @TonyNgo 还有什么需要的吗?
  • 更新你的问题而不是你的评论
  • 完成 :) @TonyNgo
  • 您也可以尝试在其他地方添加标题。为此,我经常使用 web.config:gist.github.com/Jalalhejazi/5653347

标签: c# angular asp.net-core cors signalr


【解决方案1】:

我解决了伙计们:D 问题是我的 Angular 应用程序托管在 localhost 上,这应该是我的 IPv4 IP,但它变成了 SignalR 服务器不理解的 127.0.0.1。在没有任何变化的情况下,我使用 ng serve --host 0.0.0.0 提供了角度服务,然后使用我的 IPv4 IP 连接,发挥了魅力:D 感谢您的帮助!干杯!!

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2017-05-07
    • 2018-01-01
    • 2017-05-05
    • 2020-05-30
    • 2021-11-16
    • 2021-02-24
    • 2018-07-02
    • 2022-07-18
    相关资源
    最近更新 更多