代码改变世界

MVC自定义user类

2020-12-28 11:31  胡dot  阅读(92)  评论(0编辑  收藏  举报

BaseApiController.cs

public class BaseApiController : ApiController
    {
        public HttpContextBase HttpContext
        {
            get
            {
                var context = new HttpContextWrapper(System.Web.HttpContext.Current);
                return context;
            }
        }

        protected new Principal User
        {
            get { return HttpContext.User as Principal; }
        }
    }

 

AuthenticationHelper.cs

public class AuthenticationHelper
    {
        public static void Authentication(SysUserViewModel sysUser)
        {
            var serializeModel = new PrincipalViewModel
            {
                UserId = sysUser.UserId
            };

            var serializer = new JavaScriptSerializer();

            string userData = serializer.Serialize(serializeModel);

            var authTicket = new FormsAuthenticationTicket(
                     1,
                     sysUser.UserName,
                     DateTime.Now,
                     DateTime.Now.AddHours(24),
                     false,
                     userData);

            string encTicket = FormsAuthentication.Encrypt(authTicket);
            var faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

            HttpContext.Current.Response.Cookies.Add(faCookie);
        }

        public static void Signout()
        {
            FormsAuthentication.SignOut();
        }


    }

 

Principal.cs

    public class Principal : IPrincipal
    {

        public Principal(string userName)
        {
            this.Identity = new GenericIdentity(userName);
        }

        public bool IsInRole(string role)
        {
            return false;
        }

        public IIdentity Identity { get; private set; }

        public string UserId { get; set; }

        public SysUserViewModel SysUserInfo { get; set; }
    }

 

当controller继承了baseApiController的时候就可以直接使用User.来获取对象

登录成功时调用

AuthenticationHelper.Authentication(new Models.ViewModels.SysUserViewModel { UserId = user.UserId.ToString(), UserName = user.Name });

 

退出登录时调用

AuthenticationHelper.Signout();