Published: 19 May 2010
By: Brian Mains

An overview of ASP.NET MVC 2.0 Attributes.

Contents [hide]

The ASP.NET MVC 2 Series

  • Introduction to ASP.NET MVC 2.0 In this article, we'll begin examining the new features of ASP.NET MVC 2.0 by comparing what ASP.NET MVC offers against its predecessor, ASP.NET web forms.
  • ASP.NET MVC 2.0 User Interfaces The next part to this article series on MVC 2.0 is the user interface. We saw in the last article some basics on the changes of the user interface, which we'll delve into more in this article series. Here we will begin to look at how developers can construct the view user interface.
  • ASP.NET MVC 2.0 Using Multiple Actions Brian Mains explains how to use multiple actions in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Templating Templating is now in the ASP.NET MVC 2.0 framework, for .NET framework 3.5 and 4.0. We are going to take a look at these features.
  • ASP.NET MVC 2.0 Attributes An overview of ASP.NET MVC 2.0 Attributes.
  • ASP.NET MVC 2.0 Validation An overview of validation in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Areas A look at ASP.NET MVC 2.0 Areas.
  • ASP.NET MVC 2.0 and AJAX Part 1 ASP.NET MVC makes working with AJAX really easy; it's quite impressive how powerful the framework can be. JQuery adds extra features and makes AJAX calls really easy; we'll see that all here soon.
  • ASP.NET MVC 2.0 and AJAX Part 2 In this article, we are going to look at how you can utilize AJAX in your views, and utilize a concept called unobtrusive JavaScript to take advantage of a variety of situations. ASP.NET MVC provides AJAX features very easily as we previously saw, but this comes with a caveat, and it has mostly to do with the planning of the implementation. We’re going to examine these concerns in this article.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 1 In this article, we'll examine using the ADO.NET Entity Framework (ADO.NET EF). The 4.0 version has received some major upgrades, with some major API enhancements and fixes for most of the pain points within the designer.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 2 Out of the .NET framework 4.0 comes many great enhancements, the ADO.NET entity framework (ADO.NET EF) is among the top. The framework has improved upon some of the previous bugs (in version 1), as well as enhanced the API, including many new LINQ-to-SQL-like improvements. We're going to examine using these API features to create a generic version of of a data repository.
  • Complexity in ASP.NET MVC, Part 1: Dealing With Large Models At times, every developer has a web forms page or MVC view that ends up getting pretty complex, for various reasons. Whether it pulls in and integrates a lot of data (such as a portal page) or allows users to edit a lot of information, applications require data, and the amount of data grows over time. It’s a simple reality. We’re going to examine what a larger ASP.NET MVC view looks like, and some actions we can take to keep the model instantiation code as slim as possible.
  • Complexity in ASP.NET MVC, Part 2: Plan your AJAX Carefully Brian Mains discusses management of Ajax requests in ASP.NET MVC.
  • Using DI Containers in ASP.NET MVC How to use Dependency Injection containers in ASP.NET MVC.
  • Using Microsoft Unity in ASP.NET MVC Brian Mains continues his asp.net series with the unity application block.
  • Introduction

    ASP.NET MVC can be considered a development shift toward an aspect-oriented programming style of development. While aspect-oriented programming (AOP) has been around for some time, it is relatively new to the ASP.NET development platform (at least officially by Microsoft). Within this methocology, one of the core development ideas is the injection of external resources and the use of attributes to signal code that runs before, after, or on the error of a specific method defining this attribute.

    Continuing the MVC 2.0 series, I've tried to give you a correlation between web forms and MVC, how the two act similarly. This is one area where the two do not co-relate without the use of an external library, for various reasons. First, an MVC request invokes a method within a controller. At this given time, the controller is not running within a lifecycle of sorts, or at least within a page lifecycle. A single method handles the responsibility of the current request. The framework knows when this request starts and ends, making it easy to run code that executes before and after the action method. This is opposite of web forms, which utilizes a lifecycle approach with a custom class that inherits from page. ASP.NET web forms expose an object model for its various controls that can be interacted with at various points through the page lifecycle.

    Secondly, the MVC framework provides extensibility points into the core platform, allowing you to modify the execution of, or take control of, what happens during that execution. In web forms, the framework hides a lot of those details. It's with ASP.NET 4.0 that some extensibility points are opening up to the developer.

    Defining Attributes

    Attributes are applied to a controller's class definition, or the action method itself. The following both are valid applications of an attribute:

    Listing 1: Defining attributes

    It's up to the attribute to control where the attribute can be defined (this is built-in to the .NET framework and is not an MVC-specific feature per se). An attribute itself looks like the following:

    Listing 2: Defining an attribute

    An attribute specifies an AttributeUsage attribute of its own, listing the targets its valid for (at the class, property, method level, etc.). An attribute can have constructors (the default parameters of the attribute), or supply properties. If a property has a setter, it can be applied with the <PropertyName> = <Value> syntax in C# (or with the := notation in VB) within the attribute declaration, if that property doesn't get set in the constructor.

    How MVC Uses Attributes

    A class called the ControllerActionInvoker is responsible for invoking an action method within a controller. When the browser makes a request to the controller and action method via routing, this controller factory finds the controller and assigns an instance of this action invoker to the controller for processing the request. The action invoker executes the action and result, and is responsible for finding any special attributes to run during the request lifecycle.

    What are these "special" attributes? There are multiple types of attributes specific to the MVC platform. Here are some of the different types of attributes.

    ActionMethodSelector Attributes

    This type of attribute controls the how the framework finds an action method. Only one action method can be found when invoking it from the browser; if multiple references to action methods are found an exception will be thrown, except for with the help of this attribute. This type of attribute helps weed out action methods to get list down to the correct one.

    As an example, let's look at some of the new attributes that inherit from ActionMethodSelectorAttribute. The HttpGet, HttpPost, HttpDelete, and HttpPut attributes implement this base class, and controls how the correct action methods get called. For instance, take a look at the following methods below:

    Listing 3: Get/Post Operations

    MVC gives you raw control over the requests to the server; when the browser makes a GET request to the server (requesting the page by the URL), the action method with the HttpGet attribute executes and returns a ViewResult, whereas a post operation of a form (typically by submitting a form on the web page) calls the action method with the HttpPost attribute. Without these attributes, both action methods could be called, resulting in an error.

    Filter Attributes

    This attribute type provides more control over the execution details. All filters of the following type inherit from the FilterAttribute base class. Even though there is only one base class, there are four types of filter attributes (separated by an interface):

    • Action filters – This filter fires a method before and after executing the action. A filter of this type implements the IActionFilter interface, or inherits from the ActionFilterAttribute base class.
    • Result filters – This filter fires a method before and after executing the result. A filter of this type implements the IResultFilter interface, or inherits from the ActionFilterAttribute base class.
    • Authorization Filters – This filter fires when authorizing the action method, potentially blocking it for a variety of reasons. A filter of this type implements the IAuthorizationFilter interface.
    • Exception Filter – This filter runs when an exception occurs within the action method execution. A filter of this type implements the IExceptionFilter interface.

    Let's look at what these filters do. Applying the filters are very easy; simply add the [<Filter>] notation to an action method (<Filter> notation in VB) and supply any parameters to its constructor or using the property assignment syntax, and you are set. The filter handles the rest.

    Action/Result Filters

    Action and result filters execute a pre and post condition before and after executing the action and executing the result. The framework has a base implementation that uses both of these, the ActionFilterAttribute class. Two implementations of this exists: the AsyncTimeout attribute and the OutputCache attribute.

    This type of filter is useful to run before and after the action/result, which may be beneficial for a variety of reasons. The filter can modify the response before it executes, or record what is happening in the system and respond to it. There are a variety of options.

    Authorization Filters

    The authorization process checks whether a specific action is authorized to run. There are a variety of types of authorizations. For instance, the Authorize attribute defines the users or roles permitted to run an action method, checking the current user that they have an allowed user name, or they belong to a specific role.

    Other types of authorizations can be like the ChildActionOnly attribute, which specifies that the currently executing action method is executed within the context of another action method (how Html.Action can invoke another action method within its view). The RequireHttps is another example, ensuring the request is made with an "https" protocol. So authorizations aren't limited to just security.

    Exception Filters

    Exception filters run when an exception occurs within the action method. The default handler is the HandleError attribute, which serves up a view named Error to handle the exception, but you certainly can roll your own exception handler by creating a class that implements the IExceptionFilter interface. If you do, this creates an OnException method that runs when the exception happens.

    Creating Custom Attributes

    To really understand what goes on in a filter, we need to look at some examples of attributes we can create. Let's say certain action methods you have implemented in a controller should only be served when an AJAX call to the server is made, either using the MS AJAX framework to do so, or through a JavaScript library like JQuery. The following attribute uses a new extension method to ensure only AJAX calls are allowed.

    Whatever action method this attribute is attached to will only be selected for AJAX only callback. So if this happens to be the scenario in a controller:

    Listing 4: Using Our AJAX only attribute

    For a standard request to the Index action, an exception will be thrown because the request is a GET operation that's not an AJAX request. Additionally, if an AJAX post to the server is happening, an error might also happen too because both action methods can serve the request, but only one is allowed.

    For handling exceptions using your framework, creating a custom exception filter can be helpful. The following implementation uses a customized attribute that uses a custom logging component.

    Listing 5: Creating a Custom Exception Filter

    Logger.LogError is a simple static class that can be used in an application to log errors to the backend database. Because it's static and defined in a common library, this exception filter can use it as well as any other code (controllers, business layer components, data access code, etc.).

    Lastly, processing pre/post actions and results can be implemented via the following:

    Listing 6: A Custom Action/Result Filter

    In this example, the attribute only logs that the action method is being invoked, making it easier to debug (potentially). While not the most realistic, it opens up the possibilities. You certainly can do manipulating of the request, though some of the information passed in through the context may be readonly.

    Conclusion

    MVC is very flexible, and is incorporating the best of the software development world. Aspect-Oriented Programming (AOP) reduces code-dependency by introducing reflection-based processing and linking of components.

    MVC supports the use of attributes to handle exceptions, authorizing requests, and running code before and after an action method's request and the associated response. This adds a lot of power as the framework is fully customizable, allowing any developer to write an attribute to integrate an application's business logic into attributes.

    The ASP.NET MVC 2 Series

  • Introduction to ASP.NET MVC 2.0 In this article, we'll begin examining the new features of ASP.NET MVC 2.0 by comparing what ASP.NET MVC offers against its predecessor, ASP.NET web forms.
  • ASP.NET MVC 2.0 User Interfaces The next part to this article series on MVC 2.0 is the user interface. We saw in the last article some basics on the changes of the user interface, which we'll delve into more in this article series. Here we will begin to look at how developers can construct the view user interface.
  • ASP.NET MVC 2.0 Using Multiple Actions Brian Mains explains how to use multiple actions in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Templating Templating is now in the ASP.NET MVC 2.0 framework, for .NET framework 3.5 and 4.0. We are going to take a look at these features.
  • ASP.NET MVC 2.0 Attributes An overview of ASP.NET MVC 2.0 Attributes.
  • ASP.NET MVC 2.0 Validation An overview of validation in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Areas A look at ASP.NET MVC 2.0 Areas.
  • ASP.NET MVC 2.0 and AJAX Part 1 ASP.NET MVC makes working with AJAX really easy; it's quite impressive how powerful the framework can be. JQuery adds extra features and makes AJAX calls really easy; we'll see that all here soon.
  • ASP.NET MVC 2.0 and AJAX Part 2 In this article, we are going to look at how you can utilize AJAX in your views, and utilize a concept called unobtrusive JavaScript to take advantage of a variety of situations. ASP.NET MVC provides AJAX features very easily as we previously saw, but this comes with a caveat, and it has mostly to do with the planning of the implementation. We’re going to examine these concerns in this article.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 1 In this article, we'll examine using the ADO.NET Entity Framework (ADO.NET EF). The 4.0 version has received some major upgrades, with some major API enhancements and fixes for most of the pain points within the designer.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 2 Out of the .NET framework 4.0 comes many great enhancements, the ADO.NET entity framework (ADO.NET EF) is among the top. The framework has improved upon some of the previous bugs (in version 1), as well as enhanced the API, including many new LINQ-to-SQL-like improvements. We're going to examine using these API features to create a generic version of of a data repository.
  • Complexity in ASP.NET MVC, Part 1: Dealing With Large Models At times, every developer has a web forms page or MVC view that ends up getting pretty complex, for various reasons. Whether it pulls in and integrates a lot of data (such as a portal page) or allows users to edit a lot of information, applications require data, and the amount of data grows over time. It’s a simple reality. We’re going to examine what a larger ASP.NET MVC view looks like, and some actions we can take to keep the model instantiation code as slim as possible.
  • Complexity in ASP.NET MVC, Part 2: Plan your AJAX Carefully Brian Mains discusses management of Ajax requests in ASP.NET MVC.
  • Using DI Containers in ASP.NET MVC How to use Dependency Injection containers in ASP.NET MVC.
  • Using Microsoft Unity in ASP.NET MVC Brian Mains continues his asp.net series with the unity application block.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Brian Mains

    Brian Mains is an application developer consultant with Computer Aid Inc. He formerly worked with the Department of Public Welfare. In both places of business, he developed both windows and web applications, small and large, using the latest .NET technologies. In addition, he had spent many hou...

    This author has published 73 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
    A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
    jQuery Mobile ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    Exception Handling and .Net (A practical approach)
    Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
    JQuery Mobile Widgets Overview
    An overview of widgets in jQuery Mobile.
    Book Review: SignalR: Real-time Application Development
    A book review of SignalR by Simone.

    You might also be interested in the following related blog posts


    Applying Conditional Attributes in ASP.NET MVC Views read more
    Using Custom Data Attributes to Store JSON Data in ASP.NET MVC read more
    Using Custom Data Attributes to Store JSON Data in ASP.NET MVC read more
    Learning MVC - Part 5 Repository Pattern in MVC3 Application with Entity Framework read more
    Learning MVC Part 6: Generic Repository Pattern in MVC3 Application with Entity Framework read more
    Validating Data Using Data Annotation Attributes in ASP.NET MVC read more
    Understanding the MvcRouteHandler and MvcHandler in ASP.NET MVC read more
    A Beginner's Tutorial for Understanding Filters and Attributes in ASP.NET MVC read more
    Runtime customizable model attributes in ASP.NET MVC3 read more
    Code First with Entity Framework 5 using MVC4 and MVC Scaffold read more
    Top
     
     
     

    Please login to rate or to leave a comment.