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

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) { ... }
}
主站蜘蛛池模板: 石门县| 周口市| 东明县| 安康市| 三河市| 泾川县| 辉县市| 乌审旗| 岳池县| 江西省| 尚义县| 古蔺县| 阳高县| 仪陇县| 梅河口市| 裕民县| 北宁市| 福泉市| 紫云| 慈利县| 丘北县| 涿鹿县| 北安市| 华安县| 苏州市| 龙南县| 达尔| 新密市| 瓮安县| 峨眉山市| 武山县| 宜兰县| 永德县| 久治县| 聂拉木县| 会昌县| 香河县| 读书| 武穴市| 资源县| 涞水县|