【问题标题】:Cors issue with .NET Core, Angular, Signalr, and AWS.NET Core、Angular、Signalr 和 AWS 的 Cors 问题
【发布时间】:2019-06-15 11:41:16
【问题描述】:

我正在使用 Angular 8 客户端连接到 AWS beanstalk 托管的运行 Signalr 的 .NET Core API。

当我在本地运行我的 Angular 应用程序时,这段代码运行得非常好。但是,当我将其推送到托管时,我开始收到错误。

我收到此错误

我的 .NET Core 连接如下所示

// Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SignalRHub;

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

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
                .WithOrigins("http://<my-site>.com/"); //<my-site> is replaced with the correct domain.
            }));

            services.AddSignalR();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors("CorsPolicy");
            app.UseSignalR(routes =>
            {
                routes.MapHub<NotifyHub>("/notify");
            });

            app.UseMvc();
        }
    }
}
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SignalRHub;
using System;

namespace SignalR_Hub.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("MyPolicy")]
    public class MessageController : ControllerBase
    {
        private IHubContext<NotifyHub, ITypedHubClient> _hubContext;

        public MessageController(IHubContext<NotifyHub, ITypedHubClient> hubContext)
        {
            _hubContext = hubContext;
        }

        [HttpPost]
        public string Post([FromBody]Message msg)
        {
            string retMessage;

            try
            {
                _hubContext.Clients.All.BroadcastMessage(msg.Type, msg.Payload);
                retMessage = "Success";
            }
            catch (Exception e)
            {
                retMessage = e.ToString();
            }

            return retMessage;
        }
    }
}

我的 Angular 设置如下所示:

import { Component, OnInit } from '@angular/core';
import { MessageService } from 'primeng/api';

import * as signalR from '@aspnet/signalr';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [MessageService]
})
export class AppComponent implements OnInit {

  constructor(private messageService: MessageService) { }

  ngOnInit(): void {
    const connection = new signalR.HubConnectionBuilder()
      .configureLogging(signalR.LogLevel.Information)
      .withUrl('http://<my-aws-setup>.elasticbeanstalk.com/notify')
      .build();

    connection.start().then(function () {
      console.log('Connected!');
    }).catch(function (err) {
      return console.error(err.toString());
    });

    connection.on('BroadcastMessage', (type: string, payload: string) => {
      this.messageService.add({ severity: type, summary: payload, detail: 'Via SignalR' });
    });
  }
}

我确保我的 AWS s3 设置中没有针对 Cors 的任何内容。

我尝试过的一些事情:

  • 从 API 代码中移除 Cors,将 Cors 策略添加到 AWS s3。
  • 在 Startup.cs 中我有 .AllowAnyOrigins()。
  • 我尝试指定该标题,但似乎没有任何作用。

我在这里将所有最新代码推送到 github: Client API

【问题讨论】:

    标签: angular amazon-web-services amazon-ec2 .net-core amazon-elastic-beanstalk


    【解决方案1】:

    您需要从 URI 的末尾删除 /

    只需将http://&lt;my-site&gt;.com/ 更改为http://&lt;my-site&gt;.com 即可!

    【讨论】:

    • 除了将它移到 cors 构建器的顶部外,它不起作用。谢谢!
    【解决方案2】:

    我使用下面的代码并且可以很好地为我工作

    
        public void ConfigureServices(IServiceCollection services)
            {
                services.AddCors();
            }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
    
                app.UseCors(
                    options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
                );
            }
    

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 2020-11-24
      • 2021-01-04
      • 2020-07-30
      • 1970-01-01
      • 2020-04-06
      • 2020-09-10
      • 2019-02-02
      • 2020-04-20
      相关资源
      最近更新 更多