两个项目和javascript之间的CORS

时间:2018-08-09 10:23:25

标签: c# asp.net-core asp.net-core-2.0

我有两个应用程序:

.NET Core 2.0中的WebAPI

.NET Core 2.0中的前端MVC,它使用JavaScript发送帖子请求。

我在两个初创企业中都有

ConfigureServices
services.AddCors();
services
 .AddMvc()
 .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());


Configure
app.UseDeveloperExceptionPage();
app.UseAuthentication();

app.UseCors(builder => builder
      .AllowAnyOrigin()
      .AllowAnyMethod()
      .AllowAnyHeader()
      .AllowCredentials()
      );

app.UseMvc();

但是仍然在浏览器的控制台中显示

  

“相同来源策略”不允许您从“ http://10.1.5.6:12345/test/add”加载远程资源。 (缺少CORS标题“ Access-Control-Allow-Origin”)

2 个答案:

答案 0 :(得分:0)

当您指定.AllowCredentials()时,您需要添加.WithOrigins(“ http://frontenddomain”)。这将在Access-Control-Allow-Origin标头中添加特定的域。

否则删除.AllowCredentials(),然后AllowAnyOrigin()将起作用,因为这将在标头中添加*。

浏览器不允许凭据传递带有*来源的身份验证Cookie。因此,根据您的用例,请使用AllowCredentials + WithOrigins或仅使用AllowAnyOrigin

答案 1 :(得分:0)

请丢掉您必须得到答案的答案 [.net核心的完整详细信息]

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1

以您的情况

options.AddPolicy("AllowAllMethods",
builder =>
{
    builder.WithOrigins("http://example.com")
           .AllowAnyMethod();
});