Can't get UserManager from OwinContext in apicontroller

后端 未结 3 1700
暗喜
暗喜 2020-12-07 20:15

I\'m following a Microsoft sample to implement email validation with Identity 2.0.0

I\'m stuck at this part

public ApplicationUserManager UserManager         


        
相关标签:
3条回答
  • 2020-12-07 20:25

    I really misunderstood your question earlier. You are just missing some using statements, I think.

    The GetOwinContext().GetUserManager<ApplicationUserManager>() is in Microsoft.AspNet.Identity.Owin.

    So try add this part:

    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.AspNet.Identity; // Maybe this one too
    
    var manager = HttpContext.Current.GetOwinContext().GetUserManager<UserManager<User>>();
    
    0 讨论(0)
  • 2020-12-07 20:25

    This single line of code saved my day...

           var manager = 
           new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
    

    You can use it within a controller action to get an instance of UserManager.

    0 讨论(0)
  • 2020-12-07 20:28

    This extension method may be a better solution if you want to unit test your controllers.

    using System;
    using System.Net.Http;
    using System.Web;
    using Microsoft.Owin;
    
    public static IOwinContext GetOwinContext(this HttpRequestMessage request)
    {
        var context = request.Properties["MS_HttpContext"] as HttpContextWrapper;
        if (context != null)
        {
            return HttpContextBaseExtensions.GetOwinContext(context.Request);
        }
        return null;
    }
    

    Usage:

    public ApplicationUserManager UserManager
    {
       get
       {
          return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
       }
       private set
       {
          _userManager = value;
       }
    }
    
    0 讨论(0)
提交回复
热议问题