Use attribute to create an IP restriction request

I would like to do the following (Pseudo Code):

[InternalOnly]
public ActionResult InternalMethod()
{ //magic }

The " InternalOnly" attribute is for methods that must check the IP address of a request HttpContextfor a known value before doing anything else.

How can I create this attribute " InternalOnly"?

+3
source share
2 answers

You can create your own filter attribute:

public class InternalOnly : FilterAttribute
{
    public void OnAuthorization (AuthorizationContext filterContext)
    {
        if (!IsIntranet (filterContext.HttpContext.Request.UserHostAddress))
        {
            throw new HttpException ((int)HttpStatusCode.Forbidden, "Access forbidden.");
        }
    }

    private bool IsIntranet (string userIP)
    {
        // match an internal IP (ex: 127.0.0.1)
        return !string.IsNullOrEmpty (userIP) && Regex.IsMatch (userIP, "^127");
    }
}
+6
source

This is an example of a problem that can be solved with AOP (Aspect-Oriented Programming). For this type, I usually recommend PostSharp .

, PostSharp , , .

+1

Source: https://habr.com/ru/post/1709637/


All Articles