【发布时间】:2022-01-14 18:54:07
【问题描述】:
我在本地运行一个 C# 控制器,它服务于端点 /api。我有一个带有 Javascript 的本地 html 页面,试图从该端点获取数据。但我看到控制台出现此故障。
从源“null”访问“https://localhost:44388/api”获取 已被 CORS 策略阻止:没有“访问控制允许来源” 请求的资源上存在标头。如果一个不透明的响应 满足您的需求,将请求的模式设置为“no-cors”以获取 禁用 CORS 的资源。
在我的 C# 控制器项目中,在 Startup.cs 中,我已经在 public void ConfigureServices(IServiceCollection services) 中进行了设置
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
在 public void Configure(IApplicationBuilder app, IWebHostEnvironment env),我放了
app.UseCors(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
你能告诉我我错过了什么吗?
谢谢。
更新: 我尝试更新代码来做到这一点。但我仍然遇到同样的问题。
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllowAnyOrigin",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddControllersWithViews();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/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();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
app.UseCors("AllowAnyOrigin");
}
【问题讨论】: