我在 Signalr Hub 中收到“Access-Control-Allow-Origin”错误。项目是“.net 8”
我的program.cs 文件中有这一行。
builder.Services.AddCors(options =>
{
options.AddPolicy("CORSPolicy",
builder => builder
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.SetIsOriginAllowed((hosts) => true));
});
.
.
.
.
.
.
.
.
app.UseCors("CORSPolicy");
使用打击代码可以帮助您解决cors问题。
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
...
namespace AspCore7_Web_Identity
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
...
// Add services to the container.
builder.Services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyMethod()
.SetIsOriginAllowed(_ => true)
.AllowAnyHeader()
.AllowCredentials();
}));
...
builder.Services.AddControllersWithViews();
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// 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.UseStaticFiles();
// Use Cors here
app.UseCors("CorsPolicy");
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Messaging}/{action=Index}/{id?}");
app.MapRazorPages();
app.MapHub<MainHub>("/mainhub");
app.Run();
}
}
}
如果我在信号服务器中禁用 cors 功能,我将面临以下问题。