Created
May 24, 2013 13:28
-
-
Save sebnilsson/5643497 to your computer and use it in GitHub Desktop.
MVC-attribute to ensure certain route-value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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