Skip to content

Instantly share code, notes, and snippets.

@benfoster
Created April 9, 2012 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benfoster/2346138 to your computer and use it in GitHub Desktop.
Save benfoster/2346138 to your computer and use it in GitHub Desktop.
Validating the referrer url against a collection of route value dictionaries
public static string PreviousUrl(this UrlHelper url, string defaultUrl, RouteValueDictionary[] validRoutes)
{
var previousUrl = url.GetPreviousUrl(false);
if (previousUrl == null)
return defaultUrl;
var request = url.RequestContext.HttpContext.Request;
var stubContext = new StubHttpContextForRouting(request.ApplicationPath,
VirtualPathUtility.ToAppRelative(previousUrl.AbsolutePath));
var routeData = RouteTable.Routes.GetRouteData(stubContext);
if (validRoutes.Any(rv => Matches(routeData.Values, rv, "controller", "action")))
return previousUrl.AbsoluteUri;
return defaultUrl;
}
internal static bool Matches(RouteValueDictionary d1, RouteValueDictionary d2, params string[] keys)
{
bool match = true;
foreach (var key in keys)
{
object val1, val2;
if (d1.TryGetValue(key, out val1) && d2.TryGetValue(key, out val2))
{
if (!(val1 as string).Equals((val2 as string), StringComparison.InvariantCultureIgnoreCase))
{
match = false;
break;
}
}
}
return match;
}
internal static Uri GetPreviousUrl(this UrlHelper url, bool allowExternal)
{
var httpRequest = url.RequestContext.HttpContext.Request;
var previousUrl = httpRequest.UrlReferrer;
if (previousUrl != null && (allowExternal || url.IsLocalUrl(previousUrl.AbsoluteUri)))
{
return previousUrl;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment