本文介绍了默认设置为DisplayFormatAttribute.ConvertEmptyStringToNull为假的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是转换了一堆Web服务的Web API2。现在,我的C#code吹起来的时候,浏览器发送一个空字符串,并进入我的code转换为null。我研究,我已经找到工作,为我的全球解决方案,没有。

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.

我当然可以手动设置为我所有Web API车型每字符串,但我有几十款所以才会preFER一个全球性的解决方案。

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.

在这里去过:string.empty转换为null时传递JSON对象MVC控制器以及其他页面,并企图实现每个解决方案,但都无济于事。

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.

我怎样才能为全球的ConvertEmptyStringToNull默认设置为false?

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

推荐答案

您需要换出 ModelMetadataProvider 有一个设置 ConvertEmptyStringToNull

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

如:

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

您会在你的WebApiConfig像注册:

You would register in your WebApiConfig like:

config.Services.Replace(typeof运算(ModelMetadataProvider),新EmptyStringAllowedModelMetadataProvider());

这是由 https://gist.github.com/nakamura-to/4029706

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

这篇关于默认设置为DisplayFormatAttribute.ConvertEmptyStringToNull为假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!