为ASP.NET身份提供商设置自定义主体
问题描述:
我正在使用Microsoft.ASPNET.Identity提供程序,我想设置自定义主体。此前有FomrsAuthentication为ASP.NET身份提供商设置自定义主体
,我会做这样的事情:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if(authCookie != null)
{
using (var db = new GSCM.Logic.GSCMDatabase())
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
var id = new GenericIdentity(ticket.Name);
var principal = new VmUserLogin(id);
var found = db.LoadInternalUser(ticket.Name);
if(found != null)
{
Mapper.Map(found, principal);
}
HttpContext.Current.User = principal;
}
}
}
我可怎么办与ientity提供商
答
,而不是与身份和校长打类似的东西,我会做以下:
在您的应用所需的用户信息创建的接口
public interface ICurrentUserService
{
VmUserLogin CurrentUser{get; }
}
为您的Web项目中此界面如下
public class HttpLoggedInUserService : ICurrentUserService
{
private readonly IUserRepository _userRepository;
private VmUserLogin _currentUser;
public HttpLoggedInUserService(IUserRepository userRepository)
{
_userRepository= userRepository;
}
public VmUserLogin CurrentUser
{
get
{
if (_currentUser == null)
{
if (HttpContext.Current.Items.Contains("CurrentUser"))
return HttpContext.Current.Items["CurrentUser"] as VmUserLogin ;
var loginName = HttpContext.Current.User.Identity.Name.ToLower();
_currentUser = _userRepository.GetByLoginName(loginName);
HttpContext.Current.Items["CurrentUser"] = _currentUser ;
}
if (_currentUser == null)
{
HttpContext.Current.Response.Redirect("/NoAccess");
return null;
}
return _currentUser ;
}
}
}
实现最后,你的控制器内,只需注入ICurrentUserService
public class MyController : Controller
{
private readonly ICurrentUserService _currentUserService;
public MyController(ICurrentUserService currentUserService)
{
_currentUserService = currentUserService;
}
public ActionResult Index()
{
return View(_currentUserService.CurrentUser);
}
}
你必须使用一个IoC容器,该解决方案将允许您将当前登录的用户注入到控制器,业务层甚至数据访问层中(如果需要),并且这些层都不会知道如何回收
+0
但是之后我必须在我想要使用它的每个动作上调用它 – dagda1
+0
它将从数据库中检索用户一次,并且它将被缓存对于请求生命周期中的其余调用,如果你愿意或者可能在cookie中,你也可以将它保存在会话中。 –
为什么您需要要做到这一点? –
所以我有权访问每个控制器动作中的对象,而不必每次都加载它 – dagda1