29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

public string RangeTest(int id) {<br />

if (id > 100) {<br />

return String.Format("The id value is: {0}", id);<br />

} else {<br />

throw new ArgumentOutOfRangeException("id", id, "");<br />

}<br />

}<br />

public string FilterTest() {<br />

return "This is the FilterTest action";<br />

}<br />

protected override void OnActionExecuting(ActionExecutingContext<br />

filterContext) {<br />

timer = Stopwatch.StartNew();<br />

}<br />

protected override void OnResultExecuted(ResultExecutedContext<br />

filterContext) {<br />

timer.Stop();<br />

filterContext.HttpContext.Response.Write(<br />

string.Format("Total elapsed time: {0}",<br />

timer.Elapsed.TotalSeconds));<br />

}<br />

}<br />

}<br />

I removed the filters from the FilterTest action method because they are no longer required. The Home controller will<br />

add the profile information to the response for any action method. Figure 18-11 shows the effect of starting the application and<br />

navigating to the /Home/RangeTest/200 URL, which targets the RangeTest action without causing the exception I<br />

set up to demonstrate the HandleError filter.<br />

Figure 18-11. The effect of implementing filter methods directly in the controller<br />

This technique is most useful when you are creating a base class from which multiple controllers in your project are derived.<br />

The whole point of filtering is to put code that is required across the application in one reusable location, so using these methods in<br />

a class that will not be used as a base for controllers does not make much sense.<br />

Tip I prefer to use attributes. I like the separation between the controller logic and the filter logic. If you are looking for a way<br />

to apply a filter to all of your controllers, continue reading to see how to do that with global filters.<br />

Using Global Filters<br />

Global filters are applied to all of the action methods in all of the controllers in your application. There is a convention for setting<br />

up global filters, which is created by Visual Studio automatically when you use the MVC project template but which must be set<br />

493

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!