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

查看:14
本文介绍了访问 XMLHttpRequest 已被阻止起源 ASP.NET CORE 2.2.0/Angular 8/signalr1.0.0 [(CORS Policy-Access-Control-Allow-Origin) failed]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.net core2.2.0 上的 nugetPackage:

nugetPackage on .net core2.2.0:

signalr 1.0.0 + ASP.Core2.2.0

我正在使用角度连接使用信号器:

I'm using angular to connect use signalr:

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

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
}

我的中心类:

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);
        }
    }
}

startup.cs(配置服务):

startup.cs (ConfigureServices):

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
}

startup.cs(配置):

startup.cs (Configure):

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
}

控制器:

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;
        }
    }
}

我得到以下错误:

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

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

推荐答案

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

You should add your CORS like this:

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

注意:

顺序很重要!

这篇关于访问 XMLHttpRequest 已被阻止起源 ASP.NET CORE 2.2.0/Angular 8/signalr1.0.0 [(CORS Policy-Access-Control-Allow-Origin) failed]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆