我正在使用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(...);
}
}
答案 0 :(得分:0)
使用当前解决方案永远不会调用带有ApplicationUserManager的构造函数。更改空构造函数以调用其他构造函数。
public class MyApiController: ApiController
{
public MyApiController()
: this(new ApplicationUserManager())
{
}
THE REST OF YOUR IMPLEMENTATION GOES HERE
}
答案 1 :(得分:0)
检查您是否从启动类
正确配置了UserManagerusing 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
调用按链接配置方法ConfigureAuth在样本中,它是从owin启动方法中调用的,但是根据它的使用情况可以从global.asax.cs调用