【发布时间】:2021-11-30 09:22:29
【问题描述】:
我正在开发一个应用程序,其后端是带有 SignalR 的网络核心 API,前端是 Angular。在我的计算机上调试它按预期工作,但是当我在服务器上发布时,即使在 startup.cs 上启用它们后,它也会显示 Cors 错误。
这是我得到的错误: 从源“http://server”访问“http://server:10079/fareg/api/account”处的 XMLHttpRequest 已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头请求的资源。
谁能帮助确定我做错了什么来解决 CORS 错误?
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//add Windows authentication for http options request
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services.AddDbContext<FAContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("FADB")));
services.AddCors(options =>
{
options.AddPolicy(name: _MyCors, builder =>
{
builder
.SetIsOriginAllowed(origin => new Uri(origin).Host == "server name")
//.WithOrigins("http://server/fareg", "http://localhost:4200")
.AllowCredentials()
.AllowAnyHeader()
//.SetIsOriginAllowed(_ => true)
.AllowAnyMethod();
});
});
services.AddSignalR().AddMessagePackProtocol();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(_MyCors);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseSignalR(routes =>
{
routes.MapHub<Hubs.HubFA>("/signalr");
});
app.UseMvc();
}
}
【问题讨论】:
-
如果您启用了 Windows 身份验证并使用 IIS,最简单的选择是使用 IIS CORS 模块来允许预检请求。
标签: c# angular iis cors signalr