首页 > 解决方案 > Azure 广告身份验证 Asp.net Core 2.2 和 Angular 8.2 客户端的 CORS 问题

问题描述

我正在使用工作或学校帐户身份验证设置新的 ASP.NET Core Web API。该 API 将由 Angular 8.2 应用程序使用。我从 Nuget 添加了 CORS(Microsoft.AspNetCore.Cors - 2.2.0 版)并将我的 Startup.cs 文件配置为 AddCors 和 UseCors。我已配置为 AllowAnyOrigin、AllowAnyMethod、AllowAnyHeader。我的 UseCors 语句也在 UseMVC 语句之上。

该 API 在 Web 浏览器上独立执行时可以正常工作。但是,当我将其插入 Angular 应用程序时,我遇到了错误。

从源“ http://localhost:4200 ”访问“ https://localhost:44342/api/Values ”处的 XMLHttpRequest已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头出现在请求的资源。

为什么 AllowAnyOrigin 没有被识别?

有人能帮我吗?

标签: corsazure-active-directoryasp.net-core-webapiangular8asp.net-core-2.2

解决方案


下面的一段代码对我很有魅力:

公共无效配置(IApplicationBuilder 应用程序,IHostingEnvironment env){ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }

  app.UseAuthentication();

  app.UseCors(builder => builder
  .AllowAnyOrigin()
  .AllowAnyMethod()
  .AllowCredentials()
  .AllowAnyHeader());
  app.UseMvc();

}

我在这里找到的。

有几篇关于类似问题的帖子,这里是相同的链接,请检查并让我知道它是否对您有用。

Access-Control-Allow-Origin 标头如何工作?

在 azure 应用服务上运行的 Angular 应用未收到由 .net 核心 Web api 应用在 azure 上发送的 .AspNetCore.Antiforgery cookie

ASP.NET5、MVC 6 Cookie 未跨站点共享

希望它有所帮助,请随时在您的任何对话中标记我。


推荐阅读