I have an ApplicationController that every controller in my application inherits.
public abstract class ApplicationController : Controller
public class HomeController : ApplicationController
public class AnnouncementController : ApplicationController
My application (an IntraNet) also uses Windows Authentication and extracts the current users domain login name. When a user's login name dosen't contains site id, I need the controller to show a view preferably a small popup with site list in a dropdown for the user to select.
Question 1: Should this functionality开发者_开发知识库 be implemented in the ApplicationController so all derived classes do not need to implement this checking? If yes, how do I call this method during the derived class instantiations? Currently the ApplicationController only contains constructors and no other methods.
Question 2: How do I persist this selected site id with session and other types of persistence storage for the duration of the user session?Thanks.
If this checking needs to occur with every call, I would create an attribute and decorate the base controller class with it. Be sure to decorate your new attribute with AttributeUsage
as well, so it will be called on all inheriting controllers.
[AttributeUsage (AttributeTargets.All, Inherited = true)]
public CheckStuffAttribute : ActionFilterAttribute
{
// This is one method you can override to get access
// to everything going on before any actions are executed.
public override void OnActionExecuting (ActionExecutingContext filterContext)
{
// Do your checks, or whatever you need, here
}
}
...
[CheckStuff]
public abstract class ApplicationController : Controller { ... }
As for your second question, you can create properties on the base class that use Session as their backing store.
[CheckStuff]
public abstract class ApplicationController : Controller
{
public string DataToKeepAlive
{
get { return (string)Session["MyKey"]; }
set { Session["MyKey"] = value; }
}
}
Making the properties public will give your custom attributes access to them.
精彩评论