我在 IIS 中托管了一个 WebAPI,现在因为我需要从任何地方访问我的 API,所以我创建了一个 azure 代理,但每次我使用 UI 发出请求时,都会收到此错误:
启动.cs
配置服务
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder
.SetIsOriginAllowed((string v) => _ = true)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
配置
app.UseSerilogRequestLogging();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
如果我在 IIS 所在的网络中运行前端代码,而不是调用代理,而是调用 API 的本地主机,它就可以正常工作。
最佳答案
您需要在ConfigureServices中添加mycors
规则。更多详情,您可以阅读the offical document .
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>options.AddPolicy("mycors",
p => p.AllowAnyOrigin())
);
services.AddControllersWithViews();
}
然后在Configure
函数中应用mycors
。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
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();
}
//*****apply mycors****
app.UseCors("mycors");
//*********************
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
我解构了我的两个项目。你可以看源码,我已经实现了跨域功能。
关于c# - Azure 代理,请求 IIS 托管 API 时出现 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62518597/