All, In my application design, Some the actions of Controller classes will call the same method firstly whenever it was called. the code snippet looks like below . please review it .thanks.
public class Controller1 : Controller
{
public ActionResult Action1()
{
FunctionA(); //This function must be called firstly.This function is defined somewhere.
return View("a1");
}
public ActionResult Action2()
{
FunctionA();
return View("a2");
}
}
public class Controller2 : Controller
{
public ActionResult Action3()
{
FunctionA();
return View("a3");
}
public ActionResult Action4()
{
FunctionB();
return View("a4");
}
}
In current case , Action1,Action2 in Controller1 and Action3 in Controller2 will call the same FunctionA() , Based on the DRY theory, It is better to define a base controller or method something , I don’t know how to make it in Asp.net MVC4. Please help me .thanks.
Only you can answer this question because essentially the answer is dependant on your design.
If your
FunctionAmethod is specific to that controller then you could introduce a base class. However, you could alternatively use a helper class or even just an extension method (if it’s generic enough) to achieve your DRY architecture.In terms of how to call it in your action, if it must be run before the action is executed then I would suggest introducing a custom ActionFilterAttribute which you can use to decorate each action e.g.
Or if it has to be run before every action on that particular controller, just decorate the controller e.g.