how to get Identity PasswordOptions in ASP.NET MVC

2019-07-15 04:49发布

问题:

I want to read the Identity PasswordOptions that are configured in Startup.cs from an MVC Controller. My PasswordOptions is configured like this:

services.AddIdentity<ApplicationUser, IdentityRole>(config => {
        config.Password.RequireDigit = true;
        config.Password.RequiredLength = 8;
        config.Password.RequireNonAlphanumeric = true;
});

How do I then read the RequireDigit, PasswordLength, and RequireNonAlphanumeric properties in a Controller or elsewhere in the app?

Using ASP.NET Core 1.0.1.

回答1:

Simply inject IOptions<IdentityOptions> interface to any class or controller's constructor like this:

 public class MyController : Controller
 {
     private readonly IOptions<IdentityOptions> _identityOptions;
     public MyContoller(IOptions<IdentityOptions> identityOptions)
     {
         _identityOptions=identityOptions?.Value ?? new IdentityOptions();         
     }

     public MyAction()
     {
         var length=_identityOptions.Value.Password.RequiredLength;
     }
 }