Angular 9和.NET Core-从源localhost:4200的访问已被CORS策略阻止

时间:2020-07-30 03:16:23

标签: angular asp.net-core-mvc cors

我在Angular 9中有应用程序,在.NET Core 3.1中有后端 当我想向有角度的客户提出请求时:

updated

private httpHeaders: HttpHeaders; constructor(private httpClient: HttpClient, @Inject('BASE_URL') private baseUrl: string) { this.httpHeaders = new HttpHeaders({ 'Access-Control-Allow-Origin': '*' }); } return this.httpClient.get<any>(`${environment.apiUrl}/findUser/GetUsers?name=${name}&lastname=${lastname}`, { headers: this.httpHeaders, reportProgress: true, observe: 'events' }); 中,我的设置如下:

Startup.cs

在控制器中:

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

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

但这不起作用:

[HttpGet]
[Route("getUsers")]
public IEnumerable<UserAccountDTO> GetUsers(string name, string lastname)
{}

这是请求:

  Access to XMLHttpRequest at 'http://localhost:20677/findUser/GetUsers?
name=&lastname=John' from origin 'http://localhost:4200' has been blocked by CORS
 policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

6 个答案:

答案 0 :(得分:1)

我认为是,参见the docs

//in ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
   services.AddCors(options =>
   {
        options.AddPolicy(
           name: "AllowOrigin",
           builder =>{
              builder.AllowAnyOrigin()
                     .AllowAnyMethod()
                     .AllowAnyHeader();
         });
    });
}
//in Configure
public void Configure(IApplicationBuilder app)
{
    app.UseCors("AllowOrigin");
}

注意:收到确认后,我更新了分析服务-在UseCors中省略了双引号-

答案 1 :(得分:0)

您使用代理文件,创建proxy.config.json

{
  "/api/*": {
    "target": "http://localhost:20677/api",
    "pathRewrite": {
      "^/api": ""
    },
    "changeOrigin": true,
    "secure": false,
    "logLevel": "debug"
  }
}

并与

一起使用
ng serve --proxy-config proxy.config.json

答案 2 :(得分:0)

我在几个项目中都使用了它,对我来说效果很好。

int f[n+1];
f[0] = 0;
f[1] = 1;
for (int k = 2; k <= n; k++)
  f[k] = f[k-2] + f[k-1];
return f[n];

注意:此代码位于statUp.cs

答案 3 :(得分:0)

Startup.cs中,我添加了:

services.AddCors();

    app.UseRouting();

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



    // custom jwt auth middleware
    app.UseMiddleware<JwtMiddleware>();

我有两个控制器:

WheaterController generated by Visual Studio:
[EnableCors()]
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
       [HttpGet]
       [Route("getwheater")]
       public IEnumerable<WeatherForecast> Get()
       {
       }
}

由我创建的控制器:

[EnableCors()]
    [ApiController]
    [Route("[controller]")]
    public class FindUserController : ControllerBase
    {
       [HttpGet]
       [Route("getusers2")]
       public IEnumerable<UserAccountDTO> GetUsers2()
       {
           return new List<UserAccountDTO>();
       }
    }

当我从Angular向WheaterController调用请求时,它可以工作,但是当我调用FindUserController时,出现上述错误:cors等。 两个控制器之间的区别是什么?


现在我知道问题出在哪里。 在构造函数中,我具有在依赖注入中未在Startup.cs中添加的接口,而Visual向我显示了类似CORS的错误 感谢您的帮助。

答案 4 :(得分:0)

步骤1 安装nugut包Microsoft.AspNetCore.Cors

第2步 添加
services.AddCors();

在startup.cs中的ConfigureServices下

第3步 添加

    app.UseCors(x => x
                .AllowAnyMethod()
                .AllowAnyHeader()
                .SetIsOriginAllowed(origin => true) // allow any origin
                .AllowCredentials());

在startup.cs中的“配置”下

答案 5 :(得分:-2)

您似乎对CORS的理解是错误的。我看到您的客户端代码在其请求中添加了CORS标头,但这是它的工作方式。

  • 浏览器知道从(http:// localhost:4200)下载该应用的位置
  • 浏览器知道应用程序在哪里向(http:// localhost:20677 / findUser / GetUsers? name =&lastname = John)
  • 浏览器发现这些不同
  • 在浏览器根据您的代码请求获取/发布/向http://localhost:20677/findUser/GetUsers? name=&lastname=John进行任何操作之前,浏览器首先向:4200处的服务器发出单独的请求OPTIONS http://localhost:20677/findUser/GetUsers? name=&lastname=John
  • 这就像说:“嘿20677,这个应用程序在其他网站上为我提供的服务正在尝试从您那里获取数据。您在世界上哪些网站允许这样做?”
  • 如果站点20677上显示“我们允许4200”或“我们允许任何”,则请求将成功。如果网站说了什么,或者什么也没说(对选项的响应中没有Access-Control-Allow-Origin标头),那么浏览器平台会拒绝对您的代码执行GET / POST / ETC想做

如果您在控制台中看到此消息,则表示服务器 20677 并未添加OPS响应请求的CORS标头。检查20677服务器的配置,并使用开发控制台查看其发送的标头