Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 22nd, 2012  |  syntax: None  |  size: 1.76 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. public static string PreviousUrl(this UrlHelper url, string defaultUrl, RouteValueDictionary[] validRoutes)
  2.         {
  3.             var previousUrl = url.GetPreviousUrl(false);
  4.  
  5.             if (previousUrl == null)
  6.                 return defaultUrl;
  7.  
  8.             var request = url.RequestContext.HttpContext.Request;
  9.             var stubContext = new StubHttpContextForRouting(request.ApplicationPath,
  10.                 VirtualPathUtility.ToAppRelative(previousUrl.AbsolutePath));
  11.  
  12.             var routeData = RouteTable.Routes.GetRouteData(stubContext);
  13.  
  14.             if (validRoutes.Any(rv => Matches(routeData.Values, rv, "controller", "action")))
  15.                 return previousUrl.AbsoluteUri;
  16.  
  17.             return defaultUrl;
  18.         }
  19.  
  20.         internal static bool Matches(RouteValueDictionary d1, RouteValueDictionary d2, params string[] keys)
  21.         {
  22.             bool match = true;  
  23.            
  24.             foreach (var key in keys)
  25.             {
  26.                 object val1, val2;
  27.                 if (d1.TryGetValue(key, out val1) && d2.TryGetValue(key, out val2))
  28.                 {
  29.                     if (!(val1 as string).Equals((val2 as string), StringComparison.InvariantCultureIgnoreCase))
  30.                     {
  31.                         match = false;
  32.                         break;
  33.                     }
  34.                 }
  35.             }
  36.  
  37.             return match;
  38.         }
  39.  
  40.         internal static Uri GetPreviousUrl(this UrlHelper url, bool allowExternal)
  41.         {
  42.             var httpRequest = url.RequestContext.HttpContext.Request;
  43.             var previousUrl = httpRequest.UrlReferrer;
  44.  
  45.             if (previousUrl != null && (allowExternal || url.IsLocalUrl(previousUrl.AbsoluteUri)))
  46.             {
  47.                 return previousUrl;
  48.             }
  49.  
  50.             return null;
  51.         }