Posted By

JohnAgan on 06/17/10


Tagged

c aspnet rest


Versions (?)

GetRESTData


 / Published in: C#
 

  1. /// <summary>
  2. /// Parses REST data from a url.
  3. /// </summary>
  4. /// <param name="Request">he Request object</param>
  5. /// <param name="Match">A url pattern to match. Example: /{Department}/{ID}</param>
  6. /// <returns>A dictionary of values matched to the pattern position</returns>
  7. public static StringDictionary GetRESTData(this HttpRequest Request, string UrlPattern)
  8. {
  9. string query = Request.PathInfo;
  10. StringDictionary parms = new StringDictionary();
  11.  
  12. if (UrlPattern.StartsWith("/")) UrlPattern = UrlPattern.Substring(1);
  13. string[] matchParms = UrlPattern.Split('/');
  14.  
  15. if (query.StartsWith("/")) query = query.Substring(1);
  16. string[] urlPath = query.Split('/');
  17.  
  18. for (int i = 0; i < matchParms.Length; i++)
  19. {
  20. string parm = matchParms[i];
  21. bool hasData = urlPath.Length > i;
  22. bool hasParm = parm.StartsWith("{") && parm.EndsWith("}");
  23. if (hasData && hasParm)
  24. {
  25. var p = parm.Substring(1, parm.Length - 2);
  26. parms[p] = urlPath[i];
  27. }
  28. }
  29. return parms;
  30. }

Report this snippet  

You need to login to post a comment.