【问题标题】:CORS in .NET CORE 2.1 - no header returned for simple configuration.NET CORE 2.1 中的 CORS - 简单配置不返回标头
【发布时间】:2018-12-02 06:44:23
【问题描述】:

我基本上遵循了这个文档: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();
    }
}

我是否遗漏了一些明显的东西?任何可能导致此问题的想法。整个事情看起来很简单,但被卡住了。

【问题讨论】:

  • 对于遇到此问题的任何人,在设置原点的“b.WithOrigins”中的协议中缺少一个斜线。

标签: .net asp.net-core cors .net-core asp.net-core-mvc


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    找到原因了。 .NET CORE 不会附加 CORS 标头,以防出现应用程序异常并且无法正确处理请求。所以 API 返回 500 没有 CORS 标头,浏览器将其处理为 CORS 错误,而不是 api 错误,这就是我错过它的原因。 有问题的配置工作正常

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-13
      • 2021-10-09
      • 2022-10-13
      • 2018-11-16
      • 2020-03-24
      • 2019-03-18
      • 2023-02-19
      • 2020-11-24
      相关资源
      最近更新 更多