Mikey
Mikey

Reputation: 133

Using Brackets in MVC4 and C#?

I'm sorry if you guys think this is a stupid question. I'm ready to take any criticism for my perceived incompetence. I'm new to C# and I can not for the life of myself find any references on this. What is this '[Authorize]' doing to the class in the code? I understand that AccountController is inheriting from Controller. I just do not understand that the Authorize is doing in the brackets. I'm assuming it is inheriting code from the System.Web.Mvc.AuthorizeAttribute as well but not sure because I can not find what the brackets mean in C# when placed before a class or method. So make my question clear, I'm asking, what is the purpose of putting anything in brackets before a class or function? Is it inheriting something? If so why not use the colon like with inheriting Controller? If someone can send link references that would be fine as well.. Any help appreciated..

[Authorize]
public class AccountController : Controller
{

I noticed the same usage with this method below. It is using [AllowAnonymous] instead..

[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;
    return View();
}

Upvotes: 1

Views: 981

Answers (1)

Eric J.
Eric J.

Reputation: 150138

The stuff in the brackets e.g. [Authorize] are called attributes. They are meta-data that can be applied (depending on which attribute you're talking about) to classes, methods and properties.

http://msdn.microsoft.com/en-us/library/z0w1kczw.aspx

Code that interacts with your code can use reflection to see which attributes have been applied, and what parameters (if any) are associated with each attribute.

In the specific examples you mention, the

[Authorize]

attribute is checked for by the MVC runtime to help control access to a controller

http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute(v=vs.108).aspx

and the

[AllowAnonymous]

attribute specifies that the specific Login method of the controller does not require authorization.

http://msdn.microsoft.com/en-us/library/system.web.mvc.allowanonymousattribute(v=vs.108).aspx

Upvotes: 6

Related Questions