我用IoC成功地将其抽象出来.我首先定义了一个类来表示当前登录的用户:
public class CurrentUser
{
public CurrentUser(IIdentity identity)
{
IsAuthenticated = identity.IsAuthenticated;
DisplayName = identity.Name;
var formsIdentity = identity as FormsIdentity;
if (formsIdentity != null)
{
UserID = int.Parse(formsIdentity.Ticket.UserData);
}
}
public string DisplayName { get; private set; }
public bool IsAuthenticated { get; private set; }
public int UserID { get; private set; }
}
在构造函数中设置其值需要IIdentity
.对于单元测试,可以添加另一个构造函数,以允许绕过IIdentity
依赖项.
然后我使用Ninject( Select 你最喜欢的IoC容器,没关系),并为IIdentity
创建了一个绑定:
Bind<IIdentity>().ToMethod(c => HttpContext.Current.User.Identity);
然后,在我的控制器内部,我在构造函数中声明依赖关系:
CurrentUser _currentUser;
public HomeController(CurrentUser currentUser)
{
_currentUser = currentUser;
}
IoC容器看到HomeController
接受CurrentUser
对象,CurrentUser
构造函数接受IIdentity
.它会自动解决依赖关系,瞧!控制器可以知道当前登录的用户是谁.对我来说,FormsAuthentication似乎很管用.您可以将此示例改编为Windows身份验证.