Hello,
I was trying to do some custom validation. and need to access dbcontext or usermanager in custom class. Can anybody help me to find the correct way of doing so.
public class ExistingUser : ValidationAttribute {
protected override ValidationResult IsValid(object value, ValidationContext validationContext){
var model = validationContext.ObjectInstance as RegisterViewModel;
if (model == null)
throw new ArgumentException("Attribute not applied on Employee");
//access context and check email exisits here.
return new ValidationResult(GetErrorMessage(validationContext));
return ValidationResult.Success;
}
private string GetErrorMessage(ValidationContext validationContext)
{
// Message that was supplied
if (!string.IsNullOrEmpty(this.ErrorMessage))
return this.ErrorMessage;
// Use generic message: i.e. The field {0} is invalid
//return this.FormatErrorMessage(validationContext.DisplayName);
// Custom message
return $"{validationContext.DisplayName} bhah bhah";
}
}
code for applicationdbcontext
namespace IdentityPoC.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
}
And Startup.cs Code
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 6;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 6;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;
options.User.RequireUniqueEmail = true;
// User settings
options.User.RequireUniqueEmail = true;
});
// Add application services.
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
}
Any help will be appreciated.
Thank You
Jose