3

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?

amit_g
  • 30,880
  • 8
  • 61
  • 118
Alex
  • 75,813
  • 86
  • 255
  • 348
  • A similar post has been answered here http://stackoverflow.com/questions/473687/restrict-access-to-a-specific-controller-by-ip-address-in-asp-net-mvc-beta – David Jun 02 '09 at 23:52

2 Answers2

6

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");
    }
}
Todd Smith
  • 17,084
  • 11
  • 59
  • 78
  • I can't get this to work.. I've written my code exactly as you have, but the attribute doesn't fire/has no effect.... Any idea? – Alex Jun 09 '09 at 00:42
1

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.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635