Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Attribute to create Request IP constraint

Tags:

c#

asp.net-mvc

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

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

The "InternalOnly" attribute is for methods that should check the HttpContext request IP for a known value before doing anything else.

How would I go about creating this "InternalOnly" attribute?

like image 624
Alex Avatar asked Sep 09 '26 22:09

Alex


2 Answers

You could create a custom 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");
    }
}
like image 192
Todd Smith Avatar answered Sep 11 '26 11:09

Todd Smith


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

Basically what PostSharp allows you to do is create attributes that you can use as markers for places in your code that you wish to insert boilerplate code.

like image 35
Andrew Hare Avatar answered Sep 11 '26 12:09

Andrew Hare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!