Search code examples
c#asp.net-identity

Add method to ApplicationUserManager


First time I use ASP.NET Identity and I probably miss something. I know how to use ApplicationUserManager (my class extending UserManager) but I want to create a method inside of it that use UserManager methods because I don't want to repeat code. Calling "base" doesn't work.

EDIT: the "base" didn't work because I had the method as static (I don't know why I wrote that). Now it doesn't give me errors but if I try to call it from my Web API Controller I get the "Does not contain a definition of ..." error.

ApplicationUserManager:

namespace BLL
{
    // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit = false,
                RequireLowercase = false,
                RequireUppercase = false,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }

        public async Task<int> RegistraPuntoScan(string userId, string sitoVisitato)
        {
            var user = await base.FindByIdAsync(userId);
            if(user != null)
            {
                var s = new Stringa(sitoVisitato);
                if (!user.URLVisitati.Contains(s))
                {
                    user.Punti++;
                    user.URLVisitati.Add(s);
                    await base.UpdateAsync(user);
                    return 1;
                }
                else
                {
                    return 2;
                }
            }
            else
            {
                return 3;
            }
        }
    }
}

Web API Controller:

namespace MyProject.Controllers.API
{
    [CustomAuthorization]
    public class PuntiController : ApiController
    {
        private ApplicationUserManager _userManager;

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        [HttpPost]
        public IHttpActionResult RegistraPuntoScan(RegisterPointScanVm vm)
        {
            ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
            var idUtente = ClaimsPrincipal.Current.Identity.GetUserId();
            var user = UserManager.FindById(idUtente);
            switch(UserManager.RegistraPuntoScan(idUtente, vm.ScannedURL))
            {
                case 1:
                    return Ok();
                case 2:
                    return Conflict();
                case 3:
                    return BadRequest();
            }
            return BadRequest();

        }


    }
}

Solution

  • I solved the problem. I was unable to call the new method because I have the ApplicationUserManager in another project and I probably forgot to delete the default ApplicationUserManager n IdentityConfig.cs, or VisualStudio created it, I don't know. I deleted IdentityConfig (I have all the classes in other projects) and referenced the right one, now everything works.