【发布时间】:2018-11-27 20:57:01
【问题描述】:
我对此一无所知。我已经研究了关于 SO 的类似问题的其他答案,但运气不佳。
我相当确定我已正确启用 CORS 以允许来自所有来源的传入请求(在本例中为 POST 请求),但我看到以下错误:
无法加载http://localhost:5000/expenses:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:4200” 使用权。响应的 HTTP 状态代码为 500。
以下是我在 webAPI 项目中启用 CORS 的方法:
Startup.cs 中的相关方法
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
services.AddDbContext<ExpensesDbContext>(options =>
options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<IBaseDa<Accounts>, AccountsDataAccess>();
services.AddTransient<IExpensesDa, ExpensesDa>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
env.EnvironmentName = "Development";
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials());
app.UseMvc();
}
如果我使用的是.AllowAnyOrigin() 和.AllowAnyMethod(),为什么会出现上述错误?
【问题讨论】:
-
看过asp.net core 2.0的回答in this question?
-
@JonathonChase 是的,我确实尝试定义我的策略并为其命名,等等对我不起作用;看到同样的错误
-
@mjwills 使用此 api 的前端位于端口 4200 后面。我试过
.WithOrigin(“http://localhost:4200”。没用:( -
看起来 HTTP 状态代码 500 可能是这里的问题 - Fiddler 将响应显示为什么?
-
你在使用 chrome 吗?
标签: c# asp.net .net asp.net-web-api asp.net-core