2016-05-27 73 views
0

新鲜出炉的c sharp,visual studio和web api。 (来自java)。web api属性标记如何工作​​

反正我正在玩视觉工作室的web api。在ValuesControler类中,我注意到它在类的顶部设置了一些属性,所以无论何时浏览器向api/values发出请求,都需要首先授权。

但究竟属性是什么?

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

我还发现路由属性,但我不能找到到底是什么属性的任何信息以及它是如何得到读取或程序的理解。

回答

1

在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.

对于授权属性检出

Authentication and Authorization in ASP.NET Web API

使用[授权]属性

网络API提供了一个内置的授权滤波器,AuthorizeAttribute。 此筛选器检查用户是否通过身份验证。如果不是,则 返回HTTP状态代码401(未授权),而不调用 操作。

对于属性路由退房

Attribute Routing in ASP.NET Web API 2

路由是网络API的一个URI相匹配的作用。 Web API 2支持 一种新的路由类型,称为属性路由。顾名思义, 属性路由使用属性来定义路由。属性路由 可让您更好地控制Web API中的URI。例如,您可以轻松创建描述资源层次结构的URI。

+0

是的,我已经读过那页,我知道如何使用它。我所要求的是“我无法找到属性标签到底是什么,以及它如何被程序读取或理解”。例如:它是一个对象,它是一个变量,它是什么? – user308553

+2

OP也可能会发现这个链接有用:http://stackoverflow.com/questions/21004932/when-are-method-attributes-evaluated –

+1

属性基本上是类的元数据。该框架将在执行其功能时通过反射来使用这些信息。 – Nkosi