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

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) { ... }
}
主站蜘蛛池模板: 冀州市| 南乐县| 黄冈市| 会同县| 图片| 铜鼓县| 伊宁市| 大同市| 左权县| 原平市| 铁力市| 无棣县| 枣庄市| 南康市| 尉犁县| 江川县| 贺兰县| 焉耆| 全州县| 新营市| 吉林省| 抚松县| 土默特右旗| 屏南县| 鄄城县| 颍上县| 阜城县| 安义县| 右玉县| 连平县| 海宁市| 宁安市| 芦山县| 衡阳县| 双城市| 晋州市| 凤庆县| 东宁县| 洪雅县| 海城市| 龙州县|