对 XMLHttpRequest 的访问已被阻止 origin 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]
.net core2.2.0 上的 nugetPackage:
signalr 1.0.0 + ASP.Core2.2.0
我正在使用 angular 连接使用 signalr:
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
}
我的中心 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(配置服务):
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(配置):
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;
}
}
}
我得到以下错误:
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
您应该在 Configure
方法中应用您的政策:
public void Configure
{
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.UseCors("MyPolicy");
}
更新:
如果您将本地主机用作 http://localhost:4200
,请尝试在您的配置中进行设置:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", build =>
{
build.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader();
}));
// ... other code is omitted for the brevity
}
}
和Configure
方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("ApiCorsPolicy");
app.UseHttpsRedirection();
app.UseMvc();
}
您应该像这样添加 CORS
:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});
注:
The order is important!
.net core2.2.0 上的 nugetPackage:
signalr 1.0.0 + ASP.Core2.2.0
我正在使用 angular 连接使用 signalr:
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
}
我的中心 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(配置服务):
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(配置):
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;
}
}
}
我得到以下错误:
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
您应该在 Configure
方法中应用您的政策:
public void Configure
{
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.UseCors("MyPolicy");
}
更新:
如果您将本地主机用作 http://localhost:4200
,请尝试在您的配置中进行设置:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", build =>
{
build.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader();
}));
// ... other code is omitted for the brevity
}
}
和Configure
方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("ApiCorsPolicy");
app.UseHttpsRedirection();
app.UseMvc();
}
您应该像这样添加 CORS
:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});
注:
The order is important!