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?
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");
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With