ASP.NET API AuthorizeAttribute过滤器属性为null

时间:2016-04-25 18:12:41

标签: c# asp.net asp.net-web-api

我正在尝试在API端点上创建IP过滤器。我的过滤器的属性最终为null,即使我将它们设置在我与控制器一起使用的属性中。有什么想法会发生什么?

我的控制器:

    [HttpGet]
    [Route("{socialAccountType:alpha:length(5,20)}")]
    [AllowAnonymous]
    [RestrictIp(AllowedIpRange = "148.20.57.0, 148.20.57.3", AllowedIps = "::1")]
    public IHttpActionResult Get(string socialAccountType, [FromUri] string c3IdString)
    {
        //do controller stuff
    }

我的过滤器:

public class RestrictIpAttribute : AuthorizeAttribute
{
    public string AllowedIpRange { get; set; }
    public string AllowedIps { get; set; }

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        IPAddress clientIpAddress = GetClientIpAddress(actionContext);

        if (!string.IsNullOrEmpty(AllowedIpRange)){
            bool isInRange = IsInRange(clientIpAddress);

            if (isInRange)
            {
                return true;
            }
        }

        if(!string.IsNullOrEmpty(AllowedIps))
        {
            string[] allowedIps = AllowedIps.Split(',');

            for (int i = 0; i < allowedIps.Length; i++)
            {
                IPAddress allowedIp;
                IPAddress.TryParse(allowedIps[i], out allowedIp);

                if(clientIpAddress == allowedIp)
                {
                    return true;
                }                    
            }                
        }
        return false;

    }

    private bool IsInRange(IPAddress clientIpAddress)
    {
        //check if in range
    }

    private IPAddress GetClientIpAddress(HttpActionContext actionContext)
    {
        //get client ip
    }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (!IsAuthorized(actionContext))
        {
            HandleUnauthorizedRequest(actionContext);
        }
    }
}

0 个答案:

没有答案