4

I am using Identity v2 and need to send an Email from Web Api Controller using the UserManager.SendAsync method which is OWIN Middleware component. But I don't know how do I access the UserManager itself in Web Api Controller Method. I am trying a similar approach like a Regular MVC controller but usermanager always null. Any suggestion please?

  public class MyApiController: ApiController
    {

        public MyApiController()
        {

        }

        public MyApiController(ApplicationUserManager userManager)
        {
            UserManager = userManager;
        }

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

        public void SendEmail()
        {

           _userManager.SendAsync(...);
        }
    }
Ammar Khan
  • 2,565
  • 6
  • 35
  • 60

2 Answers2

0

The constuctor that takes a ApplicationUserManager will never be called with your current solution. Change your empty constructor to call your other constructor.

public class MyApiController: ApiController
{

    public MyApiController()
    : this(new ApplicationUserManager())
    {

    }

 THE REST OF YOUR IMPLEMENTATION GOES HERE
}
Rikard
  • 3,828
  • 1
  • 24
  • 39
  • new ApplicationUserManager expect a parameter that is IUserStore, what I need to pass in? – Ammar Khan Jul 04 '14 at 15:35
  • new UserStore() – Rikard Jul 04 '14 at 16:38
  • UserManager now available but I am not getting Email where as the same code I am using in my Regular MVC controller to send email and it works fine. What could be possible reason? – Ammar Khan Jul 04 '14 at 18:14
  • I think you can answer that questions better than me. Maybe you have a service that implements the IIdentityMessageService – Rikard Jul 04 '14 at 19:04
  • Identityconfig.cs contain the method SendAsync under EmailService class which implement IIdentityMessageService . And it's not getting hit when I make a call from Web Api but it do through MVC controller. – Ammar Khan Jul 04 '14 at 19:07
  • And then you need to add the same config to your Web API as you have to your MVC project. – Rikard Jul 04 '14 at 19:28
  • In MVC Account controller the paramater less constructor not calling the constructor which takes a parameter ApplicationUserManager. Previously I tried the same with Web API but in that case I was getting usermanager null. Not sure what configuration is missing for web api – Ammar Khan Jul 04 '14 at 19:35
  • But your constructor in MVC with parameters doesn't get called if you dont use any DI-framework. – Rikard Jul 04 '14 at 21:06
  • So what I need to do now, I am not getting it what further configuration I need to make. Please let me know what code files you need so I updated my code. I will be highly thankful if you please help me to sort out this issue. – Ammar Khan Jul 04 '14 at 21:18
  • I did some debugging and before calling Email I tried to get the user through _userManager.FindByIdAsync(userId) and it throws an error "The entity type ApplicationUser is not part of the model for the current context". Any idea? – Ammar Khan Jul 05 '14 at 09:30
0

Check whether you have correctly configured UserManager from Startup class

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.DataProtection;
using Owin;

namespace Identity_PasswordPolicy
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            ///...

            // Configure the UserManager
            app.UseUserManagerFactory(new IdentityFactoryOptions<ApplicationUserManager>()
            {
                DataProtectionProvider = app.GetDataProtectionProvider(),
                Provider = new IdentityFactoryProvider<ApplicationUserManager>()
                {
                   OnCreate = ApplicationUserManager.Create
                }
            });

            /// ...
        }
    }
}

Like here in Startup.Auth class from asp.net identity samples https://aspnet.codeplex.com/SourceControl/latest#Samples/Identity/Identity-PasswordPolicy/Identity-PasswordPolicy/App_Start/Startup.Auth.cs

Startup is partial class and method ConfigureAuth by link is called from https://aspnet.codeplex.com/SourceControl/latest#Samples/Identity/Identity-PasswordPolicy/Identity-PasswordPolicy/Startup.cs

In sample it is called from owin startup method, but depending from hosing it could be called from global.asax.cs

Regfor
  • 8,515
  • 1
  • 38
  • 51
  • I found out, "UseUserManagerFactory" extension method not available. Do I need to install any nuget package? – Ammar Khan Jul 04 '14 at 19:28
  • You need to have nuget packages installed Microsoft.AspNet.Identity.Owin and Microsoft.AspNet.Identity.Core. I've added usings to the sample code in answer. Check it please. – Regfor Jul 06 '14 at 13:24
  • 1
    And actually this comment is right "Inside an ApiController I believe you'll want to use Request.GetOwinContext() and avoid HttpContext.Current", depending from hosting HttpContext.Current could be null, so try please to check it as well – Regfor Jul 07 '14 at 11:09