我正在使用microsoft . asp.net . identity提供程序,我想设置一个自定义主体。
以前使用formrsauthentication,我会这样做:
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;
}
}
}
如何使用身份提供程序做类似的事情
我将不处理标识符和主体,而是做以下操作:
为应用程序所需的User Information创建一个接口
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容器,这个解决方案将允许你在你的控制器,业务层甚至数据访问层注入当前登录的用户,如果你需要,这些层都不知道如何检索