Created
August 19, 2016 13:11
-
-
Save stevehobbsdev/c41596fc092f71ea5e920977bf249c1c to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Linq; | |
using System.Web; | |
using System.Web.Mvc; | |
namespace Filters | |
{ | |
[AttributeUsage(AttributeTargets.Method)] | |
public class SplitStringAttribute : ActionFilterAttribute | |
{ | |
public string Parameter { get; set; } | |
public string Delimiter { get; set; } | |
public SplitStringAttribute() | |
{ | |
Delimiter = ","; | |
} | |
public override void OnActionExecuting(ActionExecutingContext filterContext) | |
{ | |
if (filterContext.ActionParameters.ContainsKey(this.Parameter)) | |
{ | |
string value = null; | |
HttpRequestBase request = filterContext.RequestContext.HttpContext.Request; | |
if (filterContext.RouteData.Values.ContainsKey(this.Parameter) | |
&& filterContext.RouteData.Values[this.Parameter] is string) | |
{ | |
value = (string)filterContext.RouteData.Values[this.Parameter]; | |
} | |
else if (request[this.Parameter] is string) | |
{ | |
value = request[this.Parameter] as string; | |
} | |
Type listArgType = GetParameterEnumerableType(filterContext); | |
if (listArgType != null && !string.IsNullOrWhiteSpace(value)) | |
{ | |
string[] values = value.Split(Delimiter.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); | |
Type listType = typeof(List<>).MakeGenericType(listArgType); | |
dynamic list = Activator.CreateInstance(listType); | |
foreach (var item in values) | |
{ | |
try | |
{ | |
dynamic convertedValue = TypeDescriptor.GetConverter(listArgType).ConvertFromInvariantString(item); | |
list.Add(convertedValue); | |
} | |
catch (Exception ex) | |
{ | |
throw new ApplicationException(string.Format("Could not convert split string value to '{0}'", listArgType.FullName), ex); | |
} | |
} | |
filterContext.ActionParameters[this.Parameter] = list; | |
} | |
} | |
base.OnActionExecuting(filterContext); | |
} | |
private Type GetParameterEnumerableType(ActionExecutingContext filterContext) | |
{ | |
var param = filterContext.ActionParameters[this.Parameter]; | |
Type paramType = param.GetType(); | |
Type interfaceType = paramType.GetInterface(typeof(IEnumerable<>).FullName); | |
Type listArgType = null; | |
if (interfaceType != null) | |
{ | |
var genericParams = interfaceType.GetGenericArguments(); | |
if (genericParams.Length == 1) | |
{ | |
listArgType = genericParams[0]; | |
} | |
} | |
return listArgType; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment