【问题标题】:Enabling CORS in .net core Web api and angular 6在.net core Web api和angular 6中启用CORS
【发布时间】:2019-10-03 09:34:09
【问题描述】:

这里我使用来自 Angular 6 的 HTTP POST 请求,它在 .net 核心 Web API 调用中命中,但我没有将响应输出返回到 Angular 6 并且在控制台中出现错误:

"在 'http://localhost:55654/api/login/auth' 访问 XMLHttpRequest 来自原点“http://localhost:4200”已被 CORS 策略阻止: 请求中不存在“Access-Control-Allow-Origin”标头 资源。”

但我有点困惑,如果是任何CORS 启用访问问题,它不会命中 Web API 调用。但它触发了 API 调用,我没有得到响应。

Angular 6 HTTP POST 请求:

this.http.post("http://localhost:55654/api/login/auth", credentials, {
  headers: new HttpHeaders({
 "Content-Type": "application/json"
      })
  }).subscribe(response => {
      let token = (<any>response);
      localStorage.setItem("jwt", token);
    }, err => {

    });

我在.NetCore Web API中的以下方法中启用了CORS

ConfigureStartup.cs 中的方法:

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

ConfigureServicesStartup.cs 中的方法:

...
services.AddCors();
...

【问题讨论】:

  • app.UseMvc 是在 app.UseCors 之前还是之后调用的?它需要在app.UseCors之后
  • 这行得通....谢谢

标签: c# angular typescript asp.net-core


【解决方案1】:

如 cmets 中所述:

app.UseMvc 的调用必须在app.UseCors 之后

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

app.UseMvc();
...

【讨论】:

    【解决方案2】:

    我建议添加一个代理来访问您的后端。 只需将代理文件 (proxy.conf.json) 添加到您的根目录即可。

    为您的应用提供服务:ng s --proxy-config [PathToProxy]

    例如:

    {
      "/api/*": {
        "target": "http://localhost:55654",
        "secure": false,
        "logLevel": "debug"
      }
    }
    

    https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

    【讨论】:

      【解决方案3】:

      在 Startup.cs 添加 ConfigureServices:

      services.AddCors();
      

      在配置添加

      app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
      

      这解决了你的问题

      【讨论】:

      • 考虑到来自Startup.cs 的OP 代码sn-p,为什么这会有所不同?
      猜你喜欢
      • 2019-03-03
      • 2017-02-08
      • 2019-01-24
      • 1970-01-01
      • 2020-03-23
      • 2017-11-22
      • 2017-07-01
      • 2018-12-09
      • 2019-11-18
      相关资源
      最近更新 更多