Created
June 26, 2012 09:23
-
-
Save yojimbo87/2994627 to your computer and use it in GitHub Desktop.
Dynamic url parameters parsing
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web.Mvc; | |
using System.Dynamic; | |
using System.Globalization; | |
namespace Memphis.Framework.ActionFilters | |
{ | |
public class ParsePathAttribute : ActionFilterAttribute | |
{ | |
public override void OnActionExecuting(ActionExecutingContext filterContext) | |
{ | |
//Debug.WriteLine("Filter: " + filterContext.RouteData.Values["url"]); | |
dynamic parameters = new ExpandoObject() as IDictionary<string, Object>; | |
// dynamic method which returns null if specific property doesn't exist | |
parameters.GetProperty = (Func<string, object>)((string parameterName) => | |
{ | |
return ((IDictionary<string, object>)parameters).ContainsKey(parameterName) ? (parameters as IDictionary<string, Object>)[parameterName] : null; | |
}); | |
if (filterContext.RouteData.Values["url"] != null) | |
{ | |
string[] split = filterContext.RouteData.Values["url"].ToString().Split('/'); | |
// first parse the method name | |
((IDictionary<string, Object>)parameters).Add("method", split[0]); | |
// then parse the KV pairs | |
for (int i = 1; i < split.Count(); i = i + 2) | |
{ | |
if (((i + 1) < split.Count()) && !string.IsNullOrEmpty(split[i]) && !string.IsNullOrEmpty(split[i + 1])) | |
{ | |
bool tryBool; | |
float tryFloat; | |
int tryInt; | |
if (Boolean.TryParse(split[i + 1], out tryBool)) | |
{ | |
((IDictionary<string, Object>)parameters).Add(split[i], tryBool); | |
} | |
else if (Int32.TryParse(split[i + 1], out tryInt)) | |
{ | |
((IDictionary<string, Object>)parameters).Add(split[i], tryInt); | |
} | |
else if (float.TryParse(split[i + 1], NumberStyles.Any, CultureInfo.InvariantCulture, out tryFloat)) | |
{ | |
((IDictionary<string, Object>)parameters).Add(split[i], tryFloat); | |
} | |
else | |
{ | |
((IDictionary<string, Object>)parameters).Add(split[i], split[i + 1]); | |
} | |
} | |
} | |
} | |
filterContext.ActionParameters["parameters"] = parameters; | |
base.OnActionExecuting(filterContext); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment