Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I get certain code to execute before every single controller action in ASP.NET MVC 2?
    primarykey
    data
    text
    <p>I want to check some things about the state of the session, the user agent, etc, and possibly take action and return a special view BEFORE a controller method gets a chance to execute. For example:</p> <p>Most common:<br> User requests Home/Index<br> System checks to make sure x != 0.<br> x does not equal zero, so the Home/Index controller executes like normal.</p> <p>But, sometimes:<br> User requests Home/Index<br> System checks to make sure x != 0.<br> x DOES equal zero. The user must be notified and the requested controller action cannot be allowed to execute. </p> <p>I <em>think</em> this involves the use of ActionFilters. But I have read about them and I don't understand if I can preempt the controller method and return a view before it executes. I am sure I could execute code before the controller method runs, but how do I keep it from running in some instances and return a custom view, or direct to a different controller method?</p> <p>Update: I implemented RM's solution. This is what I did:</p> <pre><code>public class MyAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if (myValue == wrongValue) { filterContext.Result = new ViewResult{ViewName = "Notice"}; } base.OnActionExecuting(filterContext); } } </code></pre> <p>Now, when myValue is wrong, those users get the Notice view and the requested controller is never executed. To make this work I applied it to a ControllerBase that all my Controllers inherit from.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload