C# 在.net核心Web api和angular 6中启用CORS

C# 在.net核心Web api和angular 6中启用CORS,c#,angular,typescript,asp.net-core,C#,Angular,Typescript,Asp.net Core,在这里,我使用的是来自Angular 6的HTTP POST请求,它在.net core Web API调用中命中,但我没有将响应输出返回到Angular 6,并且在控制台中得到一个错误: “访问位于“”的XMLHttpRequest” 来自源“”已被CORS策略阻止: 请求的服务器上不存在“Access Control Allow Origin”标头 资源。” 但我有点困惑,如果它是任何CORS启用访问问题,它不会影响web API调用。但是它命中了API调用,我没有得到响应 6 HTTP P

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

“访问位于“”的XMLHttpRequest” 来自源“”已被CORS策略阻止: 请求的服务器上不存在“Access Control Allow Origin”标头 资源。”

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

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 => {

    });
Startup.cs
中的
ConfigureServices
方法:

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

Startup.cs加载项ConfigureServices时:

services.AddCors();
关于配置添加

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

这解决了您的问题

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

为您的应用程序提供:ng s--代理配置[PathToProxy]

例如:

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

如评论中所述:

调用
app.UseMvc
需要在
app.UseCors

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

app.UseMvc();
...

考虑到
Startup.cs
中OP的代码片段是
app.UseMvc
app.UseCors
之前还是之后调用的,这会有什么不同?它需要在app.UseCors之后运行。这很有效……谢谢