Created
February 19, 2013 10:07
-
-
Save juristr/4984583 to your computer and use it in GitHub Desktop.
Model Binder for properly handling null values. See this post here for more details: http://juristr.com/blog/2012/02/aspnet-mvc3-doesnt-deserialize-nullable
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
public class ModelBinder : IModelBinder | |
{ | |
private IModelBinder fallbackModelBinder; | |
public ModelBinder(IModelBinder fallbackModelBinder) | |
{ | |
this.fallbackModelBinder = fallbackModelBinder; | |
} | |
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) | |
{ | |
if (controllerContext.HttpContext.Request.HttpMethod.Equals("GET", StringComparison.InvariantCultureIgnoreCase)) | |
//|| controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) | |
{ | |
return this.fallbackModelBinder.BindModel(controllerContext, bindingContext); | |
} | |
else | |
{ | |
if (controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) | |
{ | |
//ONLY do this for POST,PUT,DELETE requests that transmit application/json | |
string bodyText; | |
using (var stream = controllerContext.HttpContext.Request.InputStream) | |
{ | |
stream.Seek(0, SeekOrigin.Begin); | |
using (var reader = new StreamReader(stream)) | |
bodyText = reader.ReadToEnd(); | |
} | |
if (string.IsNullOrEmpty(bodyText)) | |
return (null); | |
return JsonConvert.DeserializeObject(bodyText, bindingContext.ModelType, | |
new[] { new IsoDateTimeToLocalTimeConverter() { | |
Culture = new System.Globalization.CultureInfo("de-DE"), | |
DateTimeStyles = System.Globalization.DateTimeStyles.AssumeUniversal | |
}}); | |
} | |
else | |
{ | |
return this.fallbackModelBinder.BindModel(controllerContext, bindingContext); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment