Last active
August 29, 2015 14:01
-
-
Save james-dibble/34b87d8c9a1c1a692879 to your computer and use it in GitHub Desktop.
Dictionary MVC Route Handler
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; | |
using System.Web.Mvc; | |
using System.Web.Routing; | |
public class DictionaryRouteHandler<TKey, TValue> : MvcRouteHandler | |
{ | |
private readonly string _key; | |
public DictionaryRouteHandler(string key) | |
{ | |
this._key = key; | |
} | |
protected override IHttpHandler GetHttpHandler(RequestContext requestContext) | |
{ | |
var dictionaryParameter = requestContext.RouteData.Values[this._key] as string; | |
requestContext.RouteData.Values[this._key] = string.IsNullOrEmpty(dictionaryParameter) ? null : ParseUrlDictionary(dictionaryParameter); | |
return base.GetHttpHandler(requestContext); | |
} | |
private static IDictionary<TKey, TValue> ParseUrlDictionary(string dictionaryParameter) | |
{ | |
var dictionaryElements = Regex.Split(dictionaryParameter, @"([^/]+/[^/]+)+").Where(dp => Regex.IsMatch(dp, @"^[^/]+/[^/]+$")); | |
var urlDictionary = dictionaryElements.Select(ParseElement).ToDictionary(kvpk => kvpk.Key, kvpv => kvpv.Value); | |
return urlDictionary; | |
} | |
private static KeyValuePair<TKey, TValue> ParseElement(string element) | |
{ | |
var elementParts = element.Split('/'); | |
var key = (TKey) Convert.ChangeType(elementParts[0], typeof (TKey)); | |
var value = (TValue) Convert.ChangeType(elementParts[1], typeof (TValue)); | |
return new KeyValuePair<TKey, TValue>(key, value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment