Created
April 9, 2012 19:51
-
-
Save benfoster/2346138 to your computer and use it in GitHub Desktop.
Validating the referrer url against a collection of route value dictionaries
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 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