Skip to content

Instantly share code, notes, and snippets.

@nakamura-to
Created November 7, 2012 05:27
Show Gist options
  • Save nakamura-to/4029706 to your computer and use it in GitHub Desktop.
Save nakamura-to/4029706 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;
}
}
@almgwary
Copy link

thank you

@flydoos
Copy link

flydoos commented Sep 14, 2017

thanks mark

@caiogranero
Copy link

thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment