【问题标题】:.NET Core 5.0 Azure Deployment CORS Issue After Upgrade from 3.1从 3.1 升级后的 .NET Core 5.0 Azure 部署 CORS 问题
【发布时间】:2021-03-28 09:33:15
【问题描述】:

部署后,我的 Angular + .NET Core 应用程序出现 CORS 问题,我不确定如何解决。

当我尝试访问 API 端点时会出现以下消息,并且仅在我将版本从 3.1 升级到 5.0 后才会出现。

已被 CORS 政策阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

让我感到困惑的是,这只发生在部署中,而不是本地。一切都在本地按预期工作。我究竟做错了什么?我在 API 端添加了 CORS 配置的 sn-p。

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(o => o.AddPolicy("AllowAnyCorsPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        services.AddDbContext<DataContext>(x => x.UseInMemoryDatabase("TestDb"));
        services.AddMvc(options => options.EnableEndpointRouting = false);
        services.AddAutoMapper(typeof(Startup));
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
            });
        });

        // configure strongly typed settings objects
        var appSettingsSection = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettingsSection);

        // configure jwt authentication
        var appSettings = appSettingsSection.Get<AppSettings>();
        var key = Encoding.ASCII.GetBytes(appSettings.Secret);
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.Events = new JwtBearerEvents
            {
                OnTokenValidated = context =>
                {
                    var loginService = context.HttpContext.RequestServices.GetRequiredService<ILoginService>();
                    var user = loginService.GetById(context.Principal.Identity.Name);
                    if (user == null)
                    {
                        // return unauthorized if user no longer exists
                        context.Fail("Unauthorized");
                    }
                    return Task.CompletedTask;
                }
            };
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

        // configure DI for application services
        services.AddScoped<ILoginService, LoginService>();
        services.AddScoped<IMenuService, MenuService>();
        services.AddScoped<IViewSettingsService, ViewSettingsService>();
        services.AddScoped<IActionService, ActionService>();
        services.AddScoped<IUserSettingsService, UserSettingsService>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // global cors policy
        app.UseCors("AllowAnyCorsPolicy");


        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.Use(async (context, next) =>
        {
            await next();

            if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
            {                    context.Request.Path = "/index.html";
                await next();
            }

        });

        app.UseDefaultFiles();
        app.UseHttpsRedirection();
        app.UseAuthentication();
        app.UseMvc();
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test API V1");
        });
    }

【问题讨论】:

  • this is only happening in the deployment 什么意思?你在哪里部署应用程序?你能展示你完整的Configure方法吗?
  • CORS 问题仅在我将应用程序部署到 azure 后发生。配置方法在代码中
  • @kjamp 您是否使用 Azure DevOps 进行部署?
  • 是的,我正在使用 Azure DevOps 进行部署
  • @TM 不确定这是否会对您有所帮助,但我最终通过将应用服务计划中的设置更改为最新的 .net 框架版本来解决我的问题

标签: angular azure asp.net-core .net-core azure-devops


【解决方案1】:

浏览器中的 CORS 错误通常会掩盖潜在的内部服务器错误。我的猜测是您正在运行 Windows 应用服务计划并且尚未切换到早期访问运行时:

https://azure.github.io/AppService/2020/11/10/Dot-Net-5-on-App-Service.html

https://github.com/Azure/app-service-linux-docs/blob/master/Runtime_Support/early_access.md

【讨论】:

  • 尝试更改此设置,但仍有问题。
【解决方案2】:

这个问题可能是因为你只在 API 端启用了 CORS,而没有在 Azure 存储上启用 CORS。

您可以点击this document查看如何为 Azure 存储启用 CORS。

【讨论】:

  • 我在哪里可以找到这个?启用cors?文档有点混乱。我使用 azure devops 部署
猜你喜欢
  • 2020-07-30
  • 1970-01-01
  • 2019-06-14
  • 2022-06-13
  • 1970-01-01
  • 2021-02-26
  • 2020-04-06
  • 1970-01-01
  • 2017-07-05
相关资源
最近更新 更多