【问题标题】:Sudden CORS issue in Angular & .NET projectAngular 和 .NET 项目中突然出现 CORS 问题
【发布时间】:2020-04-20 16:10:12
【问题描述】:

我有一个基于 .NET Core 作为后端和 Angular 9 作为前端的 REST 服务。功能和交互一直运行良好。今天突然间,在项目中没有任何相关的变化,它就停止了工作。每次我使用登录功能时都会出现异常:

从源 localhost 访问 XMLHttpRequest 已被阻止 通过 CORS 策略:不存在“Access-Control-Allow-Origin”标头 请求的资源。

我的后端允许使用 CORS:

    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.WithOrigins("http://localhost:4200")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
    });

angular 的登录功能是:

@Injectable()
export class AuthService {
  login(credentials) {
    sessionStorage.removeItem('token');

    this.isBusy = true;

    this.http.post<any>(this.loginUrl, credentials, { observe: 'response' }).subscribe(res => {   

      this.authenticate(res.body);

    }, error => { 
      sessionStorage.removeItem('token');
      this.router.navigate(['/logout'])
    })
  }


  authenticate(res) {
    sessionStorage.setItem('token', res);

    this.router.navigate(['/']);
  }
}

我不明白为什么如果它运行了几个月后它突然停止运行。请指教。

【问题讨论】:

  • ASP.NET Core 应用程序可能已经开始抛出错误,导致返回 500。在这种情况下,可能没有设置 CORS 标头。

标签: c# angular asp.net-core angular7 angular9


【解决方案1】:

ASP .NET Core 中的中间件顺序可能是个问题。 Cors 应该在任何添加控制器或 MVC 之前。

// Correctly applies Cors
services.AddCors();
services.AddControllers();

// Doesn't apply Cors
services.AddControllers();
services.AddCors();

这同样适用于您的Configure(IApplicationBuilder, IWebHostEnvironment) 电话。我通常会将app.UseCors() 作为该方法的第一行。

【讨论】:

  • 注册 Cors 是我在 ConfigureServices(IServiceCollection 服务)中做的第一件事。此外,这一切都奏效了......
  • 这也是你在 Configure() 方法中做的第一件事吗?
猜你喜欢
  • 2020-11-24
  • 2017-05-09
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
  • 2017-09-07
  • 2013-11-16
  • 2015-12-15
相关资源
最近更新 更多