ASP.NET MVC: Action Filter to set up controller variables?

后端 未结 3 1692
终归单人心
终归单人心 2021-02-04 06:43

I have a scenario whereby with every page request I must check the session of the presence of a particular ID. If this is found I must grab a related object from the database an

3条回答
  •  梦如初夏
    2021-02-04 06:55

    Create a base controller like this

       public class MyContollerController : Controller
        {
            public DataEntity userData;
            protected override void Initialize(System.Web.Routing.RequestContext requestContext)
            {            
                base.Initialize(requestContext);
                var customId = requestContext.HttpContext.Session["key"];
                if(customId!=null)
                {
                     userData=getDataGromDataBase(customId);
                }   
                else
                {
                   //redirect User
                }     
            }
        }
    

    Now Create ur controllers like this

    public class MyDemoController : MyContollerController
    {
            public ActionResult Action1()
            { 
                 //access your data
                 this.userData
    
            }
            public ActionResult Action2()
            { 
                 //access your data
                 this.userData
    
            }
    }
    

提交回复
热议问题