Understanding Attributes in Asp.Net MVC

Earlier article was about to handle browser request from the user and then invokes related controller and actions written for that particular URL. What is to be done after these requests can also be specified by the programmer in Asp.Net MVC, as this article will discuss.

Asp.Net MVC provides a way to use some extra features for actions and controller, these features are called Attributes and Filters. We have discusses about Required attribute in creating MVC View Model using required field validations.

The first and most attribute, MVC use by default is [Authorize] which specifies which action is to be executed by authenticated users only or it may be used for whole controller. The syntax for this authorize attribute is:

Public ActionResult Profile()
return View();

Now whenever an un-authorized user will try to get access of this profile action, it will redirect the request to login page or the page specified.

Attributes can also take parameters specified in their declaration, they may be positional or named. Positional parameter corresponds to attribute’s public constructor like the one specified below. It will change the name of this action profile to Details, as specified as the parameter.

Public ActionResult Profile()
{ return View(); }

Named parameter correspond to public property or field of the respective attribute. For example authorize attribute have some named parameters like order, roles and users as written in following code:

[Authorize(Roles="Role1, Role2", Users="User1, User2")]
Public ActionResult Profile()
{ return View(); }

By specifying these named parameters, this profile action will only be accessed by the users having role "Role1" and "Role2". If we talk about the users, this action will only be accessed by only the person having username "User1" and "User2".
Attribute is a class which inherits from the abstract class System.Attribure. 
So we have to inherit from the same System.Attribute class to create our own attribute. Each attribute class (created by us) will must ends with the word "Attribute". E.g.
  • AuthorizeAttribute
  • RequiredAttribute
  • ActionNameAttribute
  • CustomizedAttribute
  • ValueCheckAttribute


Popular posts from this blog

difference between structure and union in C Language

Difference between Linear search and Binary Search in c language

Difference between static and dynamic websites