从ASP.NET CORE 2.2.0 / Angular 8 / signalr1.0.0开始,对XMLHttpRequest的访问已被阻止[[CORS Policy-Access-Control-Allow-Origin)失败] [英] 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]

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

问题描述

.p core.2.0上的

nugetPackage:



信号器1.0.0 + ASP.Core2.2.0



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



package.json: @ aspnet / signalr: 1.1。 0,



我的前角代码:

 从 @ angular / core导入{组件}; 
import *作为来自 @ aspnet / signalr的signalR;


@Component({
选择器:'app-root',
templateUrl:'./app.component.html'
})
出口类AppComponent {
Constructor(){}


private _hubConnection:signalR.HubConnection;
msgs:消息[] = [];


ngOnInit():void {
this._hubConnection = new signalR.HubConnectionBuilder()
.withUrl('http:// localhost:44390 / chatHub' )
.build();
this._hubConnection
.start()
.then(()=> console.log('连接已开始!'))
.catch(err =>控制台.log('建立连接时出错:('));

this._hubConnection.on('BroadcastMessage',(type:string,payload:string)= >> {
this .msgs.push({类型:类型,有效载荷:有效载荷});
});
}
}

导出类消息{

public类型:string
public有效负载:string
} .catch(err => console.log('建立连接时出错:('));

this._hubConnection.on('BroadcastMessage',(类型:字符串,有效载荷:字符串)=> {
this.msgs.push({类型:类型,有效载荷:有效载荷});
}) ;
}

}

出口类别消息{

public类型:string
public有效负载:string
}

我的中心班级:



<学前班= lang-cs prettyprint-override> 使用Microsoft.AspNetCore.SignalR;
使用System.Threading.Tasks;

命名空间SharAPI.Models
{
公共类ChatHub:集线器
{
公共异步任务BroadcastMessage(string msg)
{
等待this.Clients.All.SendAsync( BroadcastMessage,msg);
}
}
}

startup.cs(ConfigureServices) :

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

//其他代码
}

startup.cs(配置):

  public void Configure(IApplicationBuilder应用程序,IHostingEnvironment env)
{
app.UseResponseCompression();

if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// HSTS的默认值为30天。您可能要针对生产方案更改此设置,请参见https://aka.ms/aspnetcore-hsts。
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseSignalR(routes =>
{
route.MapHub&ChatHub>( / chatHub);

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

app.UseMvc();

//其他代码
}

控制器: p>

 使用Microsoft.AspNetCore.Cors; 
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.AspNetCore.SignalR;
使用SharAPI.Models;
使用系统;

命名空间SharAPI.Controllers
{
[Route( api / [controller])]
[ApiController]
[EnableCors( MyPolicy )]

公共类MessageController:ControllerBase
{
private ChatHub _hub;
public MessageController(ChatHub hub)
{
_hub = hub;
}
[HttpPost]
公共字符串Post([FromBody] Message msg)
{
string retMessage = string.Empty;
试试
{
_hub。 BroadcastMessage(msg.message);
retMessage =成功;
}
catch(异常e)
{
retMessage = e.ToString();
}
返回retMessage;
}
}
}

,我得到了:


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


解决方案

您应添加 CORS 像这样:

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

注意


顺序很重要!



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",

my angular front code:

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
}

my hub class:

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

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

and i get the error of:

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

解决方案

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

Note:

The order is important!

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

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