【问题标题】:Even after enabling CORS in .NetCore API gives CORS error即使在 .Net Core API 中启用 CORS 后也会出现 CORS 错误
【发布时间】:2021-01-01 19:50:01
【问题描述】:

我使用 ASP.Net Core API 和 Angular 作为前端,我必须为 .Net Core API 启用 CORS,下面是我尝试过的代码:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Enable Cors
    app.UseCors("CorsPolicy");
}

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

但是,如果我在浏览器中访问 Angular 应用程序,则会显示以下错误:

CORS 策略已阻止从源“http://my-angularapp.com”访问“http://my_testdomain/api/login”处的 XMLHttpRequest:Access 不允许请求标头字段内容类型-预检响应中的 Control-Allow-Headers。

更多细节:

我正在使用 AWS 发布这两个应用程序,并且这两个应用程序都位于两个不同的存储桶下。

Starup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WebAPI.Entities;
using WebAPI.Installers;
using WebAPI.Options;
using WebAPI.Validator;

namespace WebAPI
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            InstallExtensions.InstallServicesInAssembly(services, Configuration);
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
                c.AddPolicy("CorsPolicy",builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddFluentValidation();
           
            services.AddSwaggerGen(x =>
            {
                x.SwaggerDoc("v0", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "swagger", Version = "v0" });
            });
            services.AddSwaggerGen(x =>
            {
                x.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "swagger", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            var swaggerOption = new SwaggerOption();
            Configuration.GetSection(nameof(SwaggerOption)).Bind(swaggerOption);
            app.UseSwagger(options =>
            {
                options.RouteTemplate = swaggerOption.JsonRoute;
            });

            app.UseSwaggerUI(options =>
            {
                foreach (var uiEndpoint in swaggerOption.SwaggerUIEndpoints)
                {
                    options.SwaggerEndpoint(uiEndpoint.Endpoint, uiEndpoint.Description);
                }
            });
            
            app.UseHttpsRedirection();
            app.UseCors(options => options.AllowAnyOrigin());
            app.UseCors("CorsPolicy");
            app.UseMvc();
           
        }
    }
}

【问题讨论】:

  • 请分享您的端点设置,或者您可以添加endpoints.MapControllers().RequireCors(MyPolicy);
  • app.UseCors() 的位置也很重要,我们需要看看整个Configure方法。
  • @juunas 感谢您查看问题,我已在问题中添加了 startup.cs 文件
  • @RabbyHasan 添加了 startup.cs
  • @juunas 我需要为控制器级别添加属性吗?

标签: asp.net-core amazon-s3 cors asp.net-core-webapi


【解决方案1】:

您只需在 Configure 方法中的 app.UseHttpsRedirection() 之后添加以下代码:

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

您还应该在 ConfigureServices 方法中删除与 Cors 相关的其他代码。

【讨论】:

  • 感谢会检查并通知您
最近更新 更多