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

Sal*_*azi 4 cross-domain cors signalr asp.net-core angular

.net core2.2.0 上的 nugetPackage:

信号器 1.0.0 + ASP.Core2.2.0

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

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

我的角前代码:

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
}
Run Code Online (Sandbox Code Playgroud)

我的枢纽班:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

启动.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
}
Run Code Online (Sandbox Code Playgroud)

启动.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
}
Run Code Online (Sandbox Code Playgroud)

控制器:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到以下错误:

从源“ http://localhost:44390 ”访问 XMLHttpRequest 在“ https://localhost:44390/chatHub/negotiate ”已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:的值当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头不得为通配符“*”。XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制

这是图片

Kir*_*512 6

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

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

注意

顺序很重要!