Skip to content

Instantly share code, notes, and snippets.

@sebnilsson
Created May 24, 2013 13:28
Show Gist options
  • Save sebnilsson/5643497 to your computer and use it in GitHub Desktop.
Save sebnilsson/5643497 to your computer and use it in GitHub Desktop.
MVC-attribute to ensure certain route-value
public class EnsureRouteValueAttribute : ActionFilterAttribute
{
private readonly bool ignoreCase;
private readonly string routeValueKey;
private readonly string ensureRouteValue;
public EnsureRouteValueAttribute(string routeValueKey, string ensureRouteValue, bool ignoreCase = true)
{
this.ignoreCase = ignoreCase;
this.routeValueKey = routeValueKey;
this.ensureRouteValue = ensureRouteValue;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
object value;
filterContext.RouteData.Values.TryGetValue(routeValueKey, out value);
string routeValue = Convert.ToString(value);
var comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
if (routeValue.Equals(ensureRouteValue, comparison))
{
return;
}
var routeValues = filterContext.RouteData.Values;
routeValues[routeValueKey] = ensureRouteValue;
filterContext.Result = new RedirectToRouteResult(routeValues);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment