Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default for DisplayFormatAttribute.ConvertEmptyStringToNull to false

I just converted a bunch of web services to Web API2. Now my C# code blows up when the browser sends an empty string and it enters my code converted to null. I have researched global solutions and none that I have found work for me.

I can of course set it manually for every string in all my Web API models, but I have scores of models so would prefer a global solution.

Been here: string.empty converted to null when passing JSON object to MVC Controller and other pages and attempted to implement each solution, but to no avail.

How can I globally set the default for ConvertEmptyStringToNull to false?

like image 752
Reid Avatar asked Dec 01 '13 02:12

Reid


Video Answer


1 Answers

You need to swap out the ModelMetadataProvider with one that sets the ConvertEmptyStringToNull to false

Such as:

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;
    }
}

You would register in your WebApiConfig like:

config.Services.Replace(typeof(ModelMetadataProvider), new EmptyStringAllowedModelMetadataProvider());

This was inspired by https://gist.github.com/nakamura-to/4029706

like image 140
Brett Veenstra Avatar answered Oct 29 '22 05:10

Brett Veenstra