如何访问Web API Controller中的Identity UserManager以发送电子邮件

时间:2014-07-04 12:46:41

标签: asp.net-web-api asp.net-identity

我正在使用Identity v2,需要使用Web Api方法从UserManager.SendAsync控制器发送电子邮件,该方法是OWIN中间件组件。但我不知道如何在UserManager控制器方法中访问Web Api本身。我正在尝试类似于常规MVC控制器的方法,但用户管理器总是null。有什么建议吗?

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

2 个答案:

答案 0 :(得分:0)

使用当前解决方案永远不会调用带有ApplicationUserManager的构造函数。更改空构造函数以调用其他构造函数。

public class MyApiController: ApiController
{

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

    }

 THE REST OF YOUR IMPLEMENTATION GOES HERE
}

答案 1 :(得分:0)

检查您是否从启动类

正确配置了UserManager
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
                }
            });

            /// ...
        }
    }
}

就像来自asp.net身份样本的Startup.Auth类一样 https://aspnet.codeplex.com/SourceControl/latest#Samples/Identity/Identity-PasswordPolicy/Identity-PasswordPolicy/App_Start/Startup.Auth.cs

启动是部分类,并且从https://aspnet.codeplex.com/SourceControl/latest#Samples/Identity/Identity-PasswordPolicy/Identity-PasswordPolicy/Startup.cs

调用按链接配置方法ConfigureAuth

在样本中,它是从owin启动方法中调用的,但是根据它的使用情况可以从global.asax.cs调用