简体   繁体   English

在.net Core Web API和angular 6中启用CORS

[英]Enabling CORS in .net core Web api and angular 6

Here I'm using an HTTP POST request from Angular 6 and it is hitting in the .net core Web API call, but I'm not getting the response output back to Angular 6 and in console got an error that: 在这里,我使用的是来自Angular 6的HTTP POST请求,它在.net核心Web API调用中命中,但是我没有将响应输出返回到Angular 6并且在控制台中出现以下错误:

"Access to XMLHttpRequest at ' http://localhost:55654/api/login/auth ' from origin ' http://localhost:4200 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." “从起源' http:// localhost:4200 '对' http:// localhost:55654 / api / login / auth '处的XMLHttpRequest的访问已被CORS策略阻止:没有'Access-Control-Allow-Origin'标头存在于请求的资源上。”

But I'm a bit confused that if it is any CORS enabling access issue, it won't hit the web API call. 但是我有点困惑,如果它是任何启用访问权限的CORS ,它将不会打到Web API调用。 But it hits the API call and I'm not getting the response back. 但这打了API调用,但我没有得到响应。

Angular 6 HTTP POST request: 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 => {

    });

I've enabled the CORS in following methods in .NetCore Web API 我已通过.NetCore Web API中的以下方法启用了CORS

Configure Method in Startup.cs : Startup.cs Configure方法:

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

ConfigureServices Method in Startup.cs : Startup.cs ConfigureServices方法:

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

On Startup.cs add in ConfigureServices: 在Startup.cs上添加ConfigureServices:

services.AddCors();

On Configure add 在配置上添加

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

This solved your problem 这解决了你的问题

I would suggest to add a Proxy to access your Backend. 我建议添加一个代理来访问您的后端。 Just add an proxy-file (proxy.conf.json) to your root directory. 只需将代理文件(proxy.conf.json)添加到您的根目录即可。

Serve your App with: ng s --proxy-config [PathToProxy] 为您的应用提供以下服务:ng s --proxy-config [PathToProxy]

For example: 例如:

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

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

As mentioned in the comments: 如评论中所述:

The call to app.UseMvc needs to be AFTER app.UseCors 要将呼叫app.UseMvc必须AFTER app.UseCors

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

app.UseMvc();
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM