解决:.net core WebAPI跨域访问

什么是跨域?

跨域是指从一个域名的网页去请求另一个域名的资源。

跨域的严格一点的定义是:只要 协议,域名,端口有任何一个的不同,就被当作是跨域。

在往往运行中的WebAPI的时候报错:

XMLHttpRequest cannot load http://localhost:40786/api/values. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:51971' is therefore not allowed access.

解决方法:在Startup.cs中的ConfigureServices方法中添加:

services.AddCors(options => {
options.AddPolicy("AllowAll",
builder => {
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});

并在Configure方法中添加:app.UseCors("AllowAll");

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
  loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  loggerFactory.AddDebug();
  app.UseCors("AllowAll");
  app.UseMvc();
}

参考链接:No “Access-Control-Allow-Origin” header is present

 

posted @ 2017-08-18 15:11  luckymars  阅读(687)  评论(0编辑  收藏  举报