首页 文章

.Net Core / Angular 6 - Access-Control-Allow-Origin不允许使用Origin

提问于
浏览
1

我想知道为什么我在尝试从前端向后端发送数据时“获取Access-Control-Allow-Origin不允许原点”错误 . 在前端,我使用角度6,在后端,我使用Asp.Net Core 2.1(web api) . 我按照他们在这篇微软文章中所说的设置了一切:

https://docs.microsoft.com/pl-pl/aspnet/core/security/cors?view=aspnetcore-2.1

但它仍然无法正常工作 . 我不知道它是角度应用程序设置的一些问题,或者我只是在这里做错了 .

后端的工作原理:https://localhost:5001/

前端工作:https://localhost:4200/

.net核心应用程序 - startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => options
        .AddPolicy("AllowSpecificOrigin", p =>
            p.WithOrigins("https://localhost:4200")
                .AllowAnyMethod()
                .AllowCredentials()
                .AllowAnyHeader()));

    services.AddResponseCaching();

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
    }
    else {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();

    app.UseCors("AllowSpecificOrigin");

    app.UseResponseCaching();

    app.UseMvc();
}

我还尝试在控制器上使用[EnableCors(“AllowSpecificOrigin”)]属性,这给了我这个错误,但仍然无法正常工作 . 我不确定是否值得写,但我所有的HttpGet方法都没有任何问题 . 所以这不适用于HttpPost . 最奇怪的是,昨天一切都没有任何问题,没有对cors配置等进行任何更改,今天无法连接前端和后端 .

PS . 我也在startup.cs的services.AddMvc()下写了这个,但它也没有帮助:

services.Configure<MvcOptions>(options => {
    options.Filters.Add(new CorsAuthorizationFilterFactory(PolicyName));
});

enter image description here

enter image description here

2 回答

  • 0

    试试我的useCors

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            .......
    
    
    
            app.UseCors(cfg => { cfg.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().WithExposedHeaders("X-Metadata"); });
            app.UseAuthentication();
            app.UseMvc();
        }
    }
    
  • 0

    我检查了日志,这是ef核心的问题 . 昨天我在项目中创建了EF Migrations,当它生成数据库时,它会在属性上创建两个不需要的唯一键 . 日志错误:

    SQLite Error 19: 'UNIQUE constraint failed: Expense.FromUserId'.
    

    我在DbContext中的OnModelCreating方法中删除了这两行(这创建了额外的唯一约束),现在一切正常:

    modelBuilder.Entity<Expense>().HasOne(x => x.FromUser).WithOne();
    modelBuilder.Entity<Expense>().HasOne(x => x.ToUser).WithOne();
    

    我在浏览器中获得“Access-Control-Allow-Origin不允许来源”错误真的很奇怪 . 有人可以解释一下吗?

相关问题