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

后端 未结 3 1687
终归单人心
终归单人心 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
    
            }
    }
    
    0 讨论(0)
  • 2021-02-04 06:57

    Another way is to do that with Model Binders. Suppose that object is ShoppingCart

    //Custom Model Binder
    public class ShoppingCarModelBinder : IModelBinder
        {
            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                //TODO: retrieve model or return null;
            }
        }
     //register that binder in global.asax in application start
    
    ModelBinders.Binders.Add(typeof(ShoppingCart), new ShoppingCartBinder());
    
    // controller action
    
    public ActionResult DoStuff(ShoppingCart cart)
    {
         if(cart == null)
         {
         //whatever you do when cart is null, redirect. etc
         }
         else
         {
         // do stuff with cart
         }
    }
    

    Moreover, this is more unit testable and clear way, as this way action relies on parameters supplied from outside

    0 讨论(0)
  • 2021-02-04 07:06

    Yes, this sounds like a good application of an action filter, as you can apply it at the controller level to operate on all actions. You could also make it part of a controller base class, if you didn't want to add it to all controllers manually, or write your own controller factory which automatically applies this action filter to each controller.

    See ASP.NET MVC Pass object from Custom Action Filter to Action for passing data from an action filter to an action.

    0 讨论(0)
提交回复
热议问题