首页 > 解决方案 > .NET CORE 2.1 中的 CORS - 简单配置不返回标头

问题描述

我基本上遵循了这个文档:https ://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1试图在我的项目中正确设置它,但到目前为止没有缺乏。我想我尝试了每一种组合,包括中间人和服务,改变订单等。

在使用邮递员进行测试时,在对我的 API 端点进行 POST 调用时,我看不到任何与 CORS 相关的标头。

我正在使用 API 并在其上运行的应用程序http:/localhost:3000在尝试对 API 端点进行 POST 调用时出现 CORS 错误。

这是我的整个Startup.cs班级:

public class Startup
{
    public Startup(IHostingEnvironment hostingEnvironment, IConfiguration configuration)
    {
        HostingEnvironment = hostingEnvironment;
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
    public IHostingEnvironment HostingEnvironment { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddInjectionByAttribute();

        services.AddDbContext<MoneyTrackigContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddDbContext<UserContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("UserDbConnection")));                       

        services.AddIdentity<IdentityUser, IdentityRole>(o =>
        {
            o.Password.RequireDigit = false;
            o.Password.RequiredLength = 6;
            o.Password.RequireLowercase = false;
            o.Password.RequireNonAlphanumeric = false;
            o.Password.RequireUppercase = false;
        })
        .AddEntityFrameworkStores<UserContext>()
        .AddDefaultTokenProviders();

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
        services.AddAuthentication(o =>
        {
            o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(cfg =>
        {
            cfg.RequireHttpsMetadata = HostingEnvironment.IsDevelopment();
            cfg.SaveToken = true;
            cfg.TokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = Configuration.GetSection("JwtOptions")["JwtIssuer"],
                ValidAudience = Configuration.GetSection("JwtOptions")["JwtIssuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("JwtOptions")["JwtKey"])),
                ClockSkew = TimeSpan.Zero // remove delay of token when expire
            };
        });

        services.AddAuthorization(o =>
        {
            o.AddPolicy(Policy.DefaultUser, policy => policy.RequireClaim(ClaimName.User));
        });

        services.AddAutoMapper();

        services.AddCors();
        services.AddMvc();

    }

    // 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();
        }

        app.UseAuthentication();
        app.UseCors(b => b.WithOrigins("http:/localhost:3000").AllowAnyHeader().AllowAnyMethod());
        app.UseMvc();
    }
}

我错过了什么明显的东西吗?任何可能导致此问题的想法。整个事情看起来很简单,但被卡住了。

标签: .netasp.net-corecors.net-coreasp.net-core-mvc

解决方案


您需要在 Postman 中添加一个 Origin 标头以获得相应的响应。

在此处输入图像描述


推荐阅读