如何创建自定义身份验证属性

时间:2018-03-22 11:17:35

标签: asp.net-web-api2

如何在C#Web API中创建自定义身份验证属性

using System.Web.Http;
using System.Web.Http.Controllers;

namespace WebApiCustomAuthorization
{
    public class MyAuthorization : AuthorizeAttribute
    {
        protected override bool Authorized(HttpActionContext actionContext)
        {
             return true;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

使用System.Web.Http; 使用System.Web.Http.Controllers;

命名空间WebApiCustomAuthorization {     public class MyAuthorization:AuthorizeAttribute     {         protected override bool IsAuthorized(HttpActionContext actionContext)         {              return actionContext.Request.RequestUri.AbsoluteUri.Contains(“m = 1”)|| base.IsAuthorized(ActionContext中);         }     } }

答案 1 :(得分:0)

以下是自定义授权属性的示例代码。

public class CustomAuthorize : AuthorizeAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any() ||
            actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
            return;
        if (!actionContext.RequestContext.Principal.Identity.IsAuthenticated)
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        /// additional condition 
        base.OnAuthorization(actionContext);
    }
}