zoukankan      html  css  js  c++  java
  • MVC5 Controller构造方法获取User为空解决方法

    用如下方法获取UserId报空引用异常
    public class BaseController : Controller
    {
        protected SiteContext db = new SiteContext();
        protected Guid userId;
        public BaseController()
        {
            userId = Guid.Parse(User.Identity.GetUserId());
        }
    }
    

      

     

    由于Controller未初始化完成,User为空,重写初始化方法,在初始化(base.Initialize(requestContext);)完成的时候再去获取User即可

    解决方法:

    public class BaseController : Controller
    {
        protected SiteContext db = new SiteContext();
        protected Guid userId;
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            if (User.Identity.IsAuthenticated)
            {
                 userId =Guid.Parse(User.Identity.GetUserId());
            }
        }
    }
     
  • 相关阅读:
    django 2.0 path
    Django
    ORM
    Django简介
    web框架
    HTTP协议
    web应用
    索引
    pyMysql模块
    视图、触发器、存储过程、函数
  • 原文地址:https://www.cnblogs.com/hgmyz/p/7753449.html
Copyright © 2011-2022 走看看