为ASP.NET标识提供程序

时间:2016-09-28 11:24:26

标签: asp.net-mvc asp.net-identity

我正在使用Microsoft.ASPNET.Identity提供程序,我想设置自定义主体。

以前使用FomrsAuthentication,我会做这样的事情:

    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;
            }
        }
    }

我如何使用商品提供者

做类似的事情

1 个答案:

答案 0 :(得分:0)

我不会使用身份和校长,而是执行以下操作:

为应用程序中所需的用户信息创建一个界面

public interface ICurrentUserService
    {
        VmUserLogin  CurrentUser{get; }
    }

在您的网络项目中为此界面创建一个实现,如下所示

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容器,此解决方案将允许您在控制器,业务层甚至数据访问层中注入当前登录的用户(如果需要),这些层中的任何一个都不知道如何被重审