官术网_书友最值得收藏!

Using the [Authorize] attribute

AuthorizeAttribute will make sure if the user is authenticated or unauthenticated. Unauthorized error with HTTP status code 401 will be returned if the user is not authenticated and the corresponding action will not be invoked. Web API enables you to apply the filter in three ways. We can apply them at global level, or at the controller level, or at the individual action level.

Global authorization filter

To apply authorization filter for all Web API controllers, we need to add the AuthorizeAttribute filter to the global filter list in the Global.asax file as given below:

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new AuthorizeAttribute());
}

Controller level authorization filter

To apply an authorization filter for a specific controller, we need to decorate the controller with filter attribute as given in the following code:

// Require authorization for all actions on the controller.
[Authorize]
public class ContactsController : ApiController
{
    public IEnumerable<Contact> GetAllContacts() { ... }
    public IHttpActionResult GetContact(int id) { ... }
}

Action level authorization filter

To apply an authorization filter for specific actions, we need to add the attribute to the action method as given in the following code:

public class ContactsController : ApiController
{
    public IEnumerable<Contact> GetAllContacts() { ... }

    // Require authorization for a specific action.
    [Authorize]
    public IHttpActionResult GetContact(int id) { ... }
}
主站蜘蛛池模板: 奈曼旗| 台湾省| 四川省| 昌邑市| 定兴县| 隆回县| 定襄县| 乃东县| 广宗县| 梁平县| 泸水县| 宣武区| 江川县| 兰西县| 大英县| 乌苏市| 扎兰屯市| 泰来县| 修武县| 泰和县| 武冈市| 太湖县| 海阳市| 南川市| 兴仁县| 威远县| 射阳县| 沅陵县| 江永县| 上杭县| 福安市| 牟定县| 宜君县| 佛冈县| 武定县| 武川县| 岐山县| 延津县| 邳州市| 纳雍县| 磐石市|