29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

execute the result. You can see how I applied this filter to the Home controller in Listing 18-38.<br />

Listing 18-38. Applying the Result Filter in the HomeController.cs File<br />

...<br />

[ProfileAction]<br />

[ProfileResult]<br />

public string FilterTest() {<br />

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

}<br />

...<br />

Figure 18-9 shows the effect of starting the application and navigating to the /Home/FilterTest URL. You can see<br />

that both filters have added data to the response sent to the browser. The output from the result filter is shown after the result<br />

from the action method, of course, since the OnResultExecuted method cannot be executed by the MVC Framework<br />

until the result has been properly dealt with—which, in this case, means inserting a string value into the result.<br />

Figure 18-9. The effect of applying a result filter<br />

Using the Built-in Action and Result Filter Class<br />

The MVC Framework includes a built-in class that can be derived to create a class that is both an action and result filter. The<br />

class, called ActionFilterAttribute, is shown in Listing 18-39.<br />

Listing 18-39. The ActionFilterAttribute Class<br />

public abstract class ActionFilterAttribute : FilterAttribute,<br />

IActionFilter,<br />

IResultFilter{<br />

public virtual void OnActionExecuting(ActionExecutingContext<br />

filterContext) {<br />

}<br />

public virtual void OnActionExecuted(ActionExecutedContext<br />

filterContext) {<br />

}<br />

public virtual void OnResultExecuting(ResultExecutingContext<br />

filterContext) {<br />

}<br />

490

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

Saved successfully!

Ooh no, something went wrong!