Skip to content

Instantly share code, notes, and snippets.

@brettveenstra
Forked from nakamura-to/WebApiConfig.cs
Created April 11, 2016 19:30
Show Gist options
  • Save brettveenstra/4ccef284bdc6b599c61c1a65ec6757b4 to your computer and use it in GitHub Desktop.
Save brettveenstra/4ccef284bdc6b599c61c1a65ec6757b4 to your computer and use it in GitHub Desktop.
ModelMetadata.ConvertEmptyStringToNull in ASP.NET Web API
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Services.Replace(typeof(ModelMetadataProvider), new EmptyStringAllowedModelMetadataProvider());
}
}
public class EmptyStringAllowedModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override CachedDataAnnotationsModelMetadata CreateMetadataFromPrototype(CachedDataAnnotationsModelMetadata prototype, Func<object> modelAccessor)
{
var metadata = base.CreateMetadataFromPrototype(prototype, modelAccessor);
metadata.ConvertEmptyStringToNull = false;
return metadata;
}
protected override CachedDataAnnotationsModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName)
{
var metadata = base.CreateMetadataPrototype(attributes, containerType, modelType, propertyName);
metadata.ConvertEmptyStringToNull = false;
return metadata;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment