Semantics .NET MVC 3

I read a few examples, and before the methods I see the code with [SOMETHING], and I would like to know what it is and how it is used.

Can you define your own [SOMETHING] or is there a specific list of these things?

Here are some code examples I found that use this thing but don't explain anything.

[HandleError]

public class HomeController : Controller
{

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

Sometimes they even put parameters in it too, like

[HandleError (Order = 2)]

What is going on here. I feel this is SUPER important, but none of the guides I read explain that they just use them.

Thanks in advance.

+5
source share
3 answers

HandleError is an attribute.

Brief Introduction to Attributes

, , , , , , , . :

public class NameOfYourAttributeAttribute : Attribute {

}

, , :

[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)]
public class NameOfYourAttributeAttribute : Attribute {

}

, , . MSDN, Author (http://msdn.microsoft.com/en-us/library/z919e8tw%28v=vs .80%29.aspx):

[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple = true)]
public class Author : System.Attribute
{
    string name;
    public double version;

    public Author(string name)
    {
        this.name = name;
        version = 1.0;  // Default value
    }

    public string GetName()
    {
        return name;
    }
}

[Author("H. Ackerman")]
private class FirstClass
{
    // ...
}

// There some more classes here, see the example link...

class TestAuthorAttribute
{
    static void Main()
    {
        PrintAuthorInfo(typeof(FirstClass));
        PrintAuthorInfo(typeof(SecondClass));
        PrintAuthorInfo(typeof(ThirdClass));
    }

    private static void PrintAuthorInfo(System.Type t)
    {
        System.Console.WriteLine("Author information for {0}", t);
        System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // reflection

        foreach (System.Attribute attr in attrs)
        {
            if (attr is Author)
            {
                Author a = (Author)attr;
                System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);
            }
        }
    }
}

HandleError, :

, . HandleError , - , Error ~/Views/Shared/.

. http://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute.aspx.

+6

#. :

class SomeAttr : Attribute
{

}
+2

, , Attribute. , , .

MVC , , , , - .

For example, if you decorate your function with [HttpGet], only GET requests will be routed through it, everything else (for example, POST) will look for another function or throw an error if nothing is present.

+2
source

All Articles