ASP.NET MVC controller actions with custom parameter conversion? - c#

I want to set up a ASP.NET MVC route that looks like:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{idl}", // URL with parameters
new { controller = "Home", action = "Index", idl = UrlParameter.Optional } // Parameter defaults
);
That routes requests that look like this...
Example/GetItems/1,2,3
...to my controller action:
public class ExampleController : Controller
{
public ActionResult GetItems(List<int> id_list)
{
return View();
}
}
The question is, what do I set up to transform the idl url parameter from a string into List<int> and call the appropriate controller action?
I have seen a related question here that used OnActionExecuting to preprocess a string, but did not change the type. I don't think that will work for me here, because when I override OnActionExecuting in my controller and inspect the ActionExecutingContext parameter, I see that the ActionParameters dictionary already has an idl key with a null value- presumably, an attempted cast from string to List<int>... this is the part of the routing I want to be in control of.
Is this possible?

A nice version is to implement your own Model Binder. You can find a sample here
I try to give you an idea:
public class MyListBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
string integers = controllerContext.RouteData.Values["idl"] as string;
string [] stringArray = integers.Split(',');
var list = new List<int>();
foreach (string s in stringArray)
{
list.Add(int.Parse(s));
}
return list;
}
}
public ActionResult GetItems([ModelBinder(typeof(MyListBinder))]List<int> id_list)
{
return View();
}

Like slfan's says, a custom model binder is the way to go. Here's a another approach from my blog which is generic and supports multiples data types. It also elegantly falls back to default the model binding implementation:
public class CommaSeparatedValuesModelBinder : DefaultModelBinder
{
private static readonly MethodInfo ToArrayMethod = typeof(Enumerable).GetMethod("ToArray");
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
{
if (propertyDescriptor.PropertyType.GetInterface(typeof(IEnumerable).Name) != null)
{
var actualValue = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
if (actualValue != null && !String.IsNullOrWhiteSpace(actualValue.AttemptedValue) && actualValue.AttemptedValue.Contains(","))
{
var valueType = propertyDescriptor.PropertyType.GetElementType() ?? propertyDescriptor.PropertyType.GetGenericArguments().FirstOrDefault();
if (valueType != null && valueType.GetInterface(typeof(IConvertible).Name) != null)
{
var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(valueType));
foreach (var splitValue in actualValue.AttemptedValue.Split(new[] { ',' }))
{
list.Add(Convert.ChangeType(splitValue, valueType));
}
if (propertyDescriptor.PropertyType.IsArray)
{
return ToArrayMethod.MakeGenericMethod(valueType).Invoke(this, new[] { list });
}
else
{
return list;
}
}
}
}
return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
}
}

Related

Using default IModelBinder within custom binder in Web API 2

How do you call the default model binder within Web API in a custom IModelBinder? I know MVC has a default binder, but I can't use it with Web API. I just want to use the default Web API binder, and then run some custom logic after that (to avoid re-inventing the wheel).
public class CustomBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
// Get default binding (can't mix Web API and MVC)
var defaultMvcBinder = System.Web.ModelBinding.ModelBinders.Binders.DefaultBinder;
var result = defaultMvcBinder.BindModel(actionContext, bindingContext); // Won't work
if (result == false) return false;
// ... set additional model properties
return true;
}
}
In case others stumble on this question, I had to implement the custom model binder with activation context since there is nothing to re-use from Web API. Here is the solution I am using for my limited scenarios that needed to be supported.
Usage
The implementation below allows me to let any model optionally use JsonProperty for model binding, but if not provided, will default to just the property name. It supports mappings from standard .NET types (string, int, double, etc). Not quite production ready, but it meets my use cases so far.
[ModelBinder(typeof(AttributeModelBinder))]
public class PersonModel
{
[JsonProperty("pid")]
public int PersonId { get; set; }
public string Name { get; set; }
}
This allows the following query string to be mapped in a request:
/api/endpoint?pid=1&name=test
Implementation
First, the solution defines a mapped property to track the source property of the model and the target name to use when setting the value from the value provider.
public class MappedProperty
{
public MappedProperty(PropertyInfo source)
{
this.Info = source;
this.Source = source.Name;
this.Target = source.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName ?? source.Name;
}
public PropertyInfo Info { get; }
public string Source { get; }
public string Target { get; }
}
Then, a custom model binder is defined to handle the mapping. It caches the reflected model properties to avoid repeating the reflection on subsequent calls. It may not be quite production ready, but initial testing has been promising.
public class AttributeModelBinder : IModelBinder
{
public static object _lock = new object();
private static Dictionary<Type, IEnumerable<MappedProperty>> _mappings = new Dictionary<Type, IEnumerable<MappedProperty>>();
public IEnumerable<MappedProperty> GetMapping(Type type)
{
if (_mappings.TryGetValue(type, out var result)) return result; // Found
lock (_lock)
{
if (_mappings.TryGetValue(type, out result)) return result; // Check again after lock
return (_mappings[type] = type.GetProperties().Select(p => new MappedProperty(p)));
}
}
public object Convert(Type target, string value)
{
try
{
var converter = TypeDescriptor.GetConverter(target);
if (converter != null)
return converter.ConvertFromString(value);
else
return target.IsValueType ? Activator.CreateInstance(target) : null;
}
catch (NotSupportedException)
{
return target.IsValueType ? Activator.CreateInstance(target) : null;
}
}
public void SetValue(object model, MappedProperty p, IValueProvider valueProvider)
{
var value = valueProvider.GetValue(p.Target)?.AttemptedValue;
if (value == null) return;
p.Info.SetValue(model, this.Convert(p.Info.PropertyType, value));
}
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
try
{
var model = Activator.CreateInstance(bindingContext.ModelType);
var mappings = this.GetMapping(bindingContext.ModelType);
foreach (var p in mappings)
this.SetValue(model, p, bindingContext.ValueProvider);
bindingContext.Model = model;
return true;
}
catch (Exception ex)
{
return false;
}
}
}

Custom property binding in [FromUri] object

I use DTO objects as the parameters of requests to my JSON REST webservice, which is being migrated from WCF.
To get the products with the id=1 or the id=3 I have been using this Uri:
http://example.com/products?ids=1,3
For simplicity, I want to use existent DTO classes as [FromUri] parameter of my controller methods. For instance:
[HttpGet]
[Route("products")]
public IHttpActionResult GetProducts([FromUri] GetProductRequestParameters parameters)
{
...
}
And this is the DTO:
public class GetProductRequestParameters
{
public IEnumerable<int> Ids { get; set; }
public int FamilyId { get; set; }
}
The problem is that model binder expects something like ?Ids=1&Ids=3 instead of a "comma separated value" like ?Ids=1,3 for the property IEnumerable<int>
With the following code I've achieved to bind this kind of data if I use querystring parameters in the controller method instead of the DTO. I would prefer to use the later because DTOs can have lots of properties and I don't want to be filling in every parameter manually.
internal class CommaSeparatedIntegerCollectionModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
ValueProviderResult val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (val == null)
{
return false;
}
string s = val.AttemptedValue;
if (s == null || s.IndexOf(",", StringComparison.Ordinal) == 0)
{
bindingContext.Model = new int[] { };
}
var stringArray = s.Split(new[] { "," }, StringSplitOptions.None);
var listInt = new List<int>(stringArray.Count());
int valueInt;
foreach (string valueString in stringArray)
{
if (!int.TryParse(valueString, out valueInt))
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Values are not numeric");
return false;
}
listInt.Add(valueInt);
}
bindingContext.Model = listInt;
return true;
}
}
Is there some way I can instruct the model binder how to bind this kind of properties?

Default value for WebApi method parameters

I have ASP.NET WebAPI action method that looks like this:
[HttpGet]
public HttpResponseMessage Test([FromUri] TestRequest request)
{
request.Process();
return new HttpResponseMessage(HttpStatusCode.OK);
}
public class TestRequest
{
public string TestParam1 { get; set; }
public string TestParam2 { get; set; }
public void Process()
{
// do work
}
}
This works OK if the request URL has parameters specified, e.g. http://localhost/test?TestParam1=1. But when the query string is empty, request param is null, and I get a NullReferenceException in my method.
Is there a way to tell WebApi to always use an instance of new TestRequest() as a method parameter, even if the query string is empty?
Define a custom model binder:
public class TestRequestModelBinder : System.Web.Http.ModelBinding.IModelBinder
{
public bool BindModel(HttpActionContext actionContext,
System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(TestRequest)) return false;
bindingContext.Model = new TestRequest();
var parameters = actionContext.Request.RequestUri.ParseQueryString();
typeof(TestRequest)
.GetProperties()
.Select(property => property.Name)
.ToList()
.ForEach(propertyName =>
{
var parameterValue = parameters[propertyName];
if(parameterValue == null) return;
typeof(TestRequest).GetProperty(propertyName).SetValue(bindingContext.Model, parameterValue);
});
return bindingContext.ModelState.IsValid;
}
}
Use it:
[HttpGet]
public HttpResponseMessage Test([System.Web.Http.ModelBinding.ModelBinder(typeof(TestRequestModelBinder))] TestRequest request)
{
// your code
}
The answer of Andriy Tolstoy helped, I had to change it a little though to get some of my integer properties to work.
Here is the updated ModelBinder I used, in case it helps someone:
public class TestRequestModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(TestRequest)) return false;
bindingContext.Model = new TestRequest();
var parameters = actionContext.Request.RequestUri.ParseQueryString();
typeof(TestRequest)
.GetProperties()
.ToList()
.ForEach(property =>
{
var parameterValue = parameters[property.Name];
if (parameterValue == null) return;
typeof(TestRequest).GetProperty(property.Name).SetValue(bindingContext.Model, Convert.ChangeType(parameterValue, property.PropertyType));
});
return bindingContext.ModelState.IsValid;
}
}
The main change is to cast the value to the property's original PropertyType.
Using Null is the easiest way though not right design wise.
Else you can create custom behavior using a custom model binder for your TestRequest type. You can find loads of examples for the same.
You just need to test for null:
[HttpGet]
public HttpResponseMessage Test([FromUri] TestRequest request)
{
if (request == null)
request = new TestRequest();
var result = request.Process();
It's only possible to set default values to constants in the parameter list so it will not work as you want it to.
If you had a method signature like this you could set the default value to "ok" for example
public HttpResponseMessage Test(string request = "ok")
In your scenario, IMO, the best way is to set the parameter value as nullable and check against that in the controller
[HttpGet]
public HttpResponseMessage Test([FromUri] TestRequest? request)
{
if(request.HasValue)
{
//Do your thing
}
}

Where to find GetKeys() extension method for a ValueProvider?

I'm trying to use some code that I found on a forum for a better ModelBinder
public class BetterDefaultModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}
if (bindingContext.ValueProvider.GetKeys().All(IsRequiredRouteValue))
{
return null;
}
// Notes:
// 1) ContainsPrefix("") == true, for all value providers (even providers with no values)
// 2) ContainsPrefix(null) => ArgumentNullException
if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
{
if (string.IsNullOrEmpty(bindingContext.ModelName) || !bindingContext.FallbackToEmptyPrefix)
{
return null;
}
// We couldn't find any entry that began with the (non-empty) prefix.
// If this is the top-level element, fall back to the empty prefix.
bindingContext = new ModelBindingContext
{
ModelMetadata = bindingContext.ModelMetadata,
ModelState = bindingContext.ModelState,
PropertyFilter = bindingContext.PropertyFilter,
ValueProvider = bindingContext.ValueProvider
};
}
// Simple model = int, string, etc.; determined by calling TypeConverter.CanConvertFrom(typeof(string))
// or by seeing if a value in the request exactly matches the name of the model we're binding.
// Complex type = everything else.
ValueProviderResult vpResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (vpResult != null)
{
return BindSimpleModel(controllerContext, bindingContext, vpResult);
}
return bindingContext.ModelMetadata.IsComplexType ? BindComplexModel(controllerContext, bindingContext) : null;
}
private static bool IsRequiredRouteValue(string value)
{
return new[] { "area", "controller", "action" }.Any(s => value.Equals(s, StringComparison.OrdinalIgnoreCase));
}
}
Within all that code is this block:
if (bindingContext.ValueProvider.GetKeys().All(IsRequiredRouteValue))
{
return null;
}
There's a call in there to a method GetKeys(). I can't figure out where this method comes from, Visual Studio is telling me it doesn't exist. Am I correct in assuming this is an extension method?
Is it simply a using statement that I'm missing? Or is it likely the author of the code created their own GetKeys() extension method and failed to mention it?

MVC 3 doesn't bind nullable long

I made a test website to debug an issue I'm having, and it appears that either I'm passing in the JSON data wrong or MVC just can't bind nullable longs. I'm using the latest MVC 3 release, of course.
public class GetDataModel
{
public string TestString { get; set; }
public long? TestLong { get; set; }
public int? TestInt { get; set; }
}
[HttpPost]
public ActionResult GetData(GetDataModel model)
{
// Do stuff
}
I'm posting a JSON string with the correct JSON content type:
{ "TestString":"test", "TestLong":12345, "TestInt":123 }
The long isn't bound, it's always null. It works if I put the value in quotes, but I shouldn't have to do that, should I? Do I need to have a custom model binder for that value?
I created a testproject just to test this. I put your code into my HomeController and added this to index.cshtml:
<script type="text/javascript">
$(function () {
$.post('Home/GetData', { "TestString": "test", "TestLong": 12345, "TestInt": 123 });
});
</script>
I put a breakpoint in the GetData method, and the values were binded to the model like they should:
So I think there's something wrong with the way you send the values. Are you sure the "TestLong" value is actually sent over the wire? You can check this using Fiddler.
If you don't want to go with Regex and you only care about fixing long?, the following will also fix the problem:
public class JsonModelBinder : DefaultModelBinder {
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
{
var propertyType = propertyDescriptor.PropertyType;
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var provider = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (provider != null
&& provider.RawValue != null
&& Type.GetTypeCode(provider.RawValue.GetType()) == TypeCode.Int32)
{
var value = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(provider.AttemptedValue, bindingContext.ModelMetadata.ModelType);
return value;
}
}
return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
}
}
My colleague came up with a workaround for this. The solution is to take the input stream and use a Regex to wrap all numeric variables in quotes to trick the JavaScriptSerializer into deserialising the longs properly. It's not a perfect solution, but it takes care of the issue.
This is done in a custom model binder. I used Posting JSON Data to ASP.NET MVC as an example. You have to take care, though, if the input stream is accessed anywhere else.
public class JsonModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (!IsJSONRequest(controllerContext))
return base.BindModel(controllerContext, bindingContext);
// Get the JSON data that's been posted
var jsonStringData = new StreamReader(controllerContext.HttpContext.Request.InputStream).ReadToEnd();
// Wrap numerics
jsonStringData = Regex.Replace(jsonStringData, #"(?<=:)\s{0,4}(?<num>[\d\.]+)\s{0,4}(?=[,|\]|\}]+)", "\"${num}\"");
// Use the built-in serializer to do the work for us
return new JavaScriptSerializer().Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);
}
private static bool IsJSONRequest(ControllerContext controllerContext)
{
var contentType = controllerContext.HttpContext.Request.ContentType;
return contentType.Contains("application/json");
}
}
Then put this in the Global:
ModelBinders.Binders.DefaultBinder = new JsonModelBinder();
Now the long gets bound successfully. I would call this a bug in the JavaScriptSerializer. Also note that arrays of longs or nullable longs get bound just fine without the quotes.
You can use this model binder class
public class LongModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (string.IsNullOrEmpty(valueResult.AttemptedValue))
{
return (long?)null;
}
var modelState = new ModelState { Value = valueResult };
object actualValue = null;
try
{
actualValue = Convert.ToInt64(
valueResult.AttemptedValue,
CultureInfo.InvariantCulture
);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
In Global.asax Application_Start add these lines
ModelBinders.Binders.Add(typeof(long), new LongModelBinder());
ModelBinders.Binders.Add(typeof(long?), new LongModelBinder());
I wanted to incorporate the solution presented by Edgar but still have the features of the DefaultModelBinder. So instead of creating a new model binder I went with a different approach and replaced the JsonValueProviderFactory with a custom one. There's only a minor change in the code from the original MVC3 source code:
public sealed class NumericJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
{
IDictionary<string, object> d = value as IDictionary<string, object>;
if (d != null)
{
foreach (KeyValuePair<string, object> entry in d)
{
AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
}
return;
}
IList l = value as IList;
if (l != null)
{
for (int i = 0; i < l.Count; i++)
{
AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
}
return;
}
// primitive
backingStore[prefix] = value;
}
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
// not JSON request
return null;
}
StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
string bodyText = reader.ReadToEnd();
if (String.IsNullOrEmpty(bodyText))
{
// no JSON data
return null;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
// below is the code that Edgar proposed and the only change to original source code
bodyText = Regex.Replace(bodyText, #"(?<=:)\s{0,4}(?<num>[\d\.]+)\s{0,4}(?=[,|\]|\}]+)", "\"${num}\"");
object jsonData = serializer.DeserializeObject(bodyText);
return jsonData;
}
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
object jsonData = GetDeserializedObject(controllerContext);
if (jsonData == null)
{
return null;
}
Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
AddToBackingStore(backingStore, String.Empty, jsonData);
return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
}
private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
}
private static string MakePropertyKey(string prefix, string propertyName)
{
return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
}
}
Then to register the new value provider you need to add the following lines to your Global.asax:
ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
ValueProviderFactories.Factories.Add(new NumericJsonValueProviderFactory());

Categories