在.net核心webAPI中启用CORS

时间:2019-02-22 07:12:56

标签: c# angular asp.net-web-api cors

我已经安装了NuGet软件包Microsoft.AspNetCore.Cors 2.2.0 然后在我的.net核心webAPI Startup.cs中,执行以下操作:

public void ConfigureServices(IServiceCollection services) { 
......
services.AddCors();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors(options =>
    options.WithOrigins("http://localhost:52556")
    .AllowAnyMethod()
    .AllowAnyHeader());

    app.UseMvc();
}

然后,当我从控制台中的我的角度应用程序发送发布请求时,我看到此错误:

  

访问“ http://localhost:52556/api/PaymentDetail”处的XMLHttpRequest   来自来源“ http://localhost:4200”的信息已被CORS政策阻止:   对预检请求的响应未通过访问控制检查:否   请求中存在“ Access-Control-Allow-Origin”标头   资源。

我以为我已经启用了CORS,但似乎有一些阻止它。有什么办法可以解决这个问题?

3 个答案:

答案 0 :(得分:1)

尝试这种方式。我认为这是因为您只允许使用带有“ http://localhost:52556”的URL。使用“ *”将启用所有URL,如果需要,可以将其限制为任何特定的URL。

public void ConfigureServices(IServiceCollection services)
{
  .........................
    services.AddCors(options =>
            {
                options.AddPolicy("NoRestrictions",
                    builder => builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod());
            });;
     ...............
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<AppServerSettings> appServerSettings)
{
    ..........
    app.UseCors("NoRestrictions");
    ..........
}

答案 1 :(得分:0)

您正在为ASP主机设置Origin。

只需替换此行

options.WithOrigins("http://localhost:52556")

使用

options.WithOrigins("http://localhost:4200")

答案 2 :(得分:0)

我通过注释/属性解决了C#中的相同问题,

[System.Web.Http.Cors.EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
public class StudentsController : ApiController{}
在MVC中, 使用

// For Action, 
[HttpGet]
[EnableCors("AllowSpecificOrigin")]
public IEnumerable<string> Get(){}
// For Controller,   
[Route("api/[controller]")]
[EnableCors("AllowSpecificOrigin")]
public class ValuesController : ControllerBase{}

根据您的情况,将其替换为端口号进程4200专用的

options.WithOrigins("http://localhost:4200");

或者您可以放No Restrictions

app.UseCors("NoRestrictions");// To config
// To service
services.AddCors(options =>
{
  options.AddPolicy("NoRestrictions",
         builder => builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod());
});

检查起源, 1)检查端口号(e.g. 8080 or 8888) 2)域和子域(e.g. google.com or google.net) 3)模式(e.g. http or https)

注册来源

进入Startup.ConfigureServices并致电services.AddCors();

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}

现在启用cors, 转到Startup.Configure并致电app.UseCors(builder => builder.WithOrigins("http://google.com"));