Can't get UserManager from OwinContext in apicontroller

C#asp.net Web-Apiasp.net IdentityOwin

C# Problem Overview


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

I'm stuck at this part

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

This works in an controller but HttpContext doesn't contain any GetOwinContext method in an ApiController.

So I tried HttpContext.Current.GetOwinContext() but the method GetUserManager doesn't exist.

I can't figure out a way to get the UserManager I build in Startup.Auth.cs

// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
    //Configure the db context, user manager and role manager to use a single instance per request
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
    ...
}

this line

app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

calls the following function to configure the UserManager

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 user lockout defaults
     manager.UserLockoutEnabledByDefault = true;
     manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
     manager.MaxFailedAccessAttemptsBeforeLockout = 5;

     manager.EmailService = new EmailService();

     var dataProtectionProvider = options.DataProtectionProvider;
     if (dataProtectionProvider != null)
     {
         manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
     }
     return manager;
}

How can I access this UserManager in an ApiController?

C# Solutions


Solution 1 - C#

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>>();

Solution 2 - C#

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;
   }
}

Solution 3 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcView Question on Stackoverflow
Solution 1 - C#RikardView Answer on Stackoverflow
Solution 2 - C#moanderView Answer on Stackoverflow
Solution 3 - C#Mubsher MughalView Answer on Stackoverflow