angular - 访问 XMLHttpRequest 已被阻止源 ASP.NET CORE 2.2.0/Angular 8/signalr1.0.0 [(CORS Policy-Access-Control-Allow-Origin) failed]

标签 angular asp.net-core cors signalr cross-domain

.net core2.2.0 上的 nugetPackage:

signalr 1.0.0 + ASP.Core2.2.0

我正在使用 angular 连接使用信号器:

package.json: "@aspnet/signalr": "1.1.0",

我的 Angular 前代码:

import { Component } from '@angular/core';
import * as signalR from "@aspnet/signalr";


@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent {
    constructor() { }


    private _hubConnection: signalR.HubConnection;
    msgs: Message[] = [];


    ngOnInit(): void {
        this._hubConnection = new signalR.HubConnectionBuilder()
            .withUrl('http://localhost:44390/chatHub')
            .build();
        this._hubConnection
            .start()
            .then(() => console.log('Connection started!'))
            .catch(err => console.log('Error while establishing connection :('));

        this._hubConnection.on('BroadcastMessage', (type: string, payload: string) => {
            this.msgs.push({ Type: type, Payload: payload });
        });
    }
}

export class Message {

    public Type: string
    public Payload: string
}       .catch(err => console.log('Error while establishing connection :('));

        this._hubConnection.on('BroadcastMessage', (type: string, payload: string) => {
            this.msgs.push({ Type: type, Payload: payload });
        });
    }

}

export class Message {

    public Type: string
    public Payload: string
}

我的枢纽类:

using Microsoft.AspNetCore.SignalR; 
using System.Threading.Tasks;

namespace SharAPI.Models
{
    public class ChatHub : Hub 
    {
        public async Task BroadcastMessage(string msg)
        {
            await this.Clients.All.SendAsync("BroadcastMessage", msg);
        }
    }
}

启动.cs(配置服务):

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));
    services.AddSignalR();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    // other codes
}

启动.cs(配置):

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseResponseCompression();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseSignalR(routes =>
    {
        routes.MapHub<ChatHub>("/chatHub");

    });
    app.UseCors(options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

    app.UseMvc();

    //other codes
}

Controller :

using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SharAPI.Models;
using System;

namespace SharAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("MyPolicy")]

    public class MessageController : ControllerBase
    {
        private ChatHub _hub;
        public MessageController(ChatHub hub)
        {
            _hub  = hub ;
        }
        [HttpPost]
        public string Post([FromBody]Message msg)
        {
            string retMessage = string.Empty;
            try
            {
               _hub. BroadcastMessage(msg.message);
                retMessage = "Success";
            }
            catch (Exception e)
            {
                retMessage = e.ToString();
            }
            return retMessage;
        }
    }
}

我得到以下错误:

Access to XMLHttpRequest at 'https://localhost:44390/chatHub/negotiate' from origin 'http://localhost:44390' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute



here is the pic

最佳答案

您应该添加您的 CORS像这样:

services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://localhost:4200")
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials()
        .SetIsOriginAllowed((host) => true));
});
备注 :

The order is important!

关于angular - 访问 XMLHttpRequest 已被阻止源 ASP.NET CORE 2.2.0/Angular 8/signalr1.0.0 [(CORS Policy-Access-Control-Allow-Origin) failed],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59468525/

相关文章:

angular - Playright 使用 global-setup.ts 缓存 session 超时登录到应用程序,等待 DEBUG=0 的选择器,而 DEBUG=1 则不会超时

Angular 4 表单验证器 - minLength 和 maxLength 不适用于字段类型编号

asp.net-core - MVC网络核心3.1 : Tool to create and download PDF file

c# - 在 blazor 中改变组件属性的正确方法

rest - Angular 2 REST 请求 HTTP 状态代码 401 更改为 0

ruby-on-rails - Googlebot 在 Rails 4.1 上导致无效的跨域请求 (COR)

angular - 如何使用 CLI 创建特定版本的 Angular 项目?

angular - Ionic 和事件中选项卡栏上的 FAB

jquery - 如何修改我的 Web API 服务器代码以添加 Access-Control-Allow-Origin' header ?

entity-framework - 如何建立一对多关系的中间表?