user308553
user308553

Reputation: 1250

how does web api attribute tag work

new to c sharp, visual studio and web api. (come from java).

Anyways I'm playing around with web api from visual studio. In the ValuesControler class I notice it set something call a attribute on top of the class, so whenever a browser make a request to api/values it will need to be authorized first.

But what exactly is an attribute?

[Authorize]
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

I also found the routing attributes, but I cant find any info on what exactly is attributes and how is it getting read or understood by the program.

Upvotes: 0

Views: 1008

Answers (1)

Nkosi
Nkosi

Reputation: 247143

In c# Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). Once associated with a program entity, the attribute can be queried at run time and used in any number of ways.

For authorize attribute check out

Authentication and Authorization in ASP.NET Web API

Using the [Authorize] Attribute

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action.

For attribute routing check out

Attribute Routing in ASP.NET Web API 2

Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.

Upvotes: 1

Related Questions