添加UserManager时收到错误CORS

时间:2019-05-07 14:28:55

标签: c# asp.net-core cors

CORS策略已阻止从来源“ http://localhost:5000//register”访问“ http://localhost:4200”处的XMLHttpRequest:请求的资源上没有“ Access-Control-Allow-Origin”标头。

我在构造函数UserManager和SignInManager中添加了。然后我得到了错误。

控制器:

[Route("api/[controller]")]
[ApiController]
public class AccountController : BaseController
{
  List<User> users = new List<User>
    {
        new User { Login="admin", Password="12345", Role = "admin" },
        new User { Login="qwerty", Password="55555", Role = "user" }
    };

  public AccountController(IOptions<AWSEmailCredentials> options, UserManager<User> userManager, SignInManager<User> signInManager)
  {    }

  [HttpPost]
  public ActionResult Register([FromBody] User user)
  {
    if (ModelState.IsValid)
    {
    }
  }
}

启动:

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

public IConfiguration Configuration { get; }

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

  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
  {
    options.RequireHttpsMetadata = false;
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
      ValidateIssuer = true,
      ValidIssuer = AuthOptions.ISSUER,
      ValidateAudience = true,
      ValidAudience = AuthOptions.AUDIENCE,
      ValidateLifetime = true,

      IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
      ValidateIssuerSigningKey = true,
    };
  });

  services.AddRouting();
  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

  services.Configure<AWSCredentials>(Configuration.GetSection("AWSCredentials"));
  services.Configure<AWSEmailCredentials>(Configuration.GetSection("AWSEmailCredentials"));

  services.AddIdentity<User, IdentityRole>().AddEntityFrameworkStores<DAL.ApplicationContext>();
}

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

  app.UseCors("AllowOrigin");
  app.UseHttpsRedirection();
  app.UseStaticFiles();

  app.UseAuthentication();

  app.UseMvc();
}

}

用户:

public class User : IdentityUser
{
  public int Id { get; set; }
  public string Login { get; set; }
  public string Password { get; set; }
  public string Role { get; set; }
  public string Email { get; set; }
}

DbContext:

public class ApplicationContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Book> Books { get; set; }

public ApplicationContext()
{
  Database.EnsureCreated();
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
  if (!optionsBuilder.IsConfigured)
  {
    optionsBuilder
        .UseSqlServer(@"Data Source=xxx;Initial Catalog=Books;User id=xx;Password=xxx;");
  }
}
}

请帮助我解决此问题。

1 个答案:

答案 0 :(得分:0)

我添加了课程:

public class IdentityContext : IdentityDbContext<User>
{
  public IdentityContext(DbContextOptions<IdentityContext> options)
      : base(options) { }

  protected override void OnModelCreating(ModelBuilder builder)
  {
    base.OnModelCreating(builder);
  }
}

在启动中:

services.AddDbContext<IdentityContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<User, IdentityRole>().AddEntityFrameworkStores<DAL.IdentityContext>().AddDefaultTokenProviders();