开发者

.NET MVC 3 semantics

开发者 https://www.devze.com 2023-04-11 14:16 出处:网络
I\'m reading some examples and i keep seeing code with [SOMETHING] before methods and I\'d like to know what that\'s called and how it\'s used.

I'm reading some examples and i keep seeing code with [SOMETHING] before methods and I'd like to know what that's called and how it's used.

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

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

[HandleError]

public class HomeController : Controller
{

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

        return View();
    }

    publi开发者_开发百科c ActionResult About()
    {
        return View();
    }
}

Sometimes they even put parameters in it too like

[HandleError(Order = 2)]

Whats going on here. I feel like this is SUPER important but none of the reference books I've read explain it they just use them.

Thanks ahead of time.


HandleError is an attribute.

Brief Intro to Attributes

Attributes are contained in square brackets, prefixing classes, structs, fields, parameters, functions, and arguments, and you can define your own by inheriting from Attribute in a class. The typical format of creating an attribute is as such:

public class NameOfYourAttributeAttribute : Attribute {

}

You can also prefix your attribute definition with an attribute that defines the scope of what it can apply to:

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

}

In the example above, there really isn't that much to the class, other than it just being a decorator for a class or a struct. Consider an example from the MSDN, where classes can be given an Author attribute (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's 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);
            }
        }
    }
}

In the case of HandleError, specifically:

They provide helpful information that can be seen via reflection. In the case of HandleError, it means that if any exception is thrown within the controller, that it will render the Error view in ~/Views/Shared/.

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


These are called attributes, and are a common feature of C#. You can declare them yourself:

class SomeAttr : Attribute
{

}


They're called attributes and they're just normal classes derived from Attribute. You can most certainly define your own.

Since MVC is made with convention over configuration in mind, you can decorate your functions with attributes and the framework will try to figure out what to do with them without any more intervention from you.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号