ModelState中验证失败可空类型 [英] ModelState validation fails for nullable types

查看:177
本文介绍了ModelState中验证失败可空类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不能在应用程序的WebAPI对象,其中包含可空类型,具有空值传递的ModelState验证。错误消息是'空'的值无效DateProperty。

对象的code:

公共类TestNull
{
    公众诠释IntProperty {搞定;组; }
    公众的DateTime? DateProperty {搞定;组; }
}

控制器:

公共类TestNullController:ApiController
{
    公共TestNull获取(INT ID)
    {
        返回新TestNull(){IntProperty = 1,DateProperty = NULL};
    }    公众的Htt presponseMessage把(INT ID,TestNull值)
    {
        如果(ModelState.IsValid)
            返回Request.CreateResponse(的HTTPStatus code.OK,价值);
        其他
        {
            VAR误差=新的解释和LT;字符串的IEnumerable<串GT;>();
            的foreach(在ModelState中VAR的keyValue)
            {
                错误[keyValue.Key] = keyValue.Value.Errors.Select(E => e.ErrorMessage);
            }            返回Request.CreateResponse(的HTTPStatus code.BadRequest,错误);
        }
    }
}

请求:

  $。的getJSON(API / TestNull / 1
功能(数据){
    的console.log(数据);
    $阿贾克斯({
        网址:API / TestNull /+ data.IntProperty,
        输入:'把',
        数据类型:JSON,
        数据:数据
    });
});


解决方案

我只是在一个我自己的WebAPI项目快速测试,并传递null作为值可空类型的正常工作。我建议你​​检查正在使用像提琴手

两个有效的情况下,将工作是:

  {IntProperty:1,DateProperty:空}
{IntProperty:1} //是的,你可以简单地离开地产出

场景,将不会的工作是:

  {IntProperty:1,DateProperty:空} //注意引号
{IntProperty:1,DateProperty:未定义} //无效的JSON
{IntProperty:1,DateProperty:0} //会不会是由.NET JSON解串器PTED妥善间$ P $

如果两个默认情况下的不那么我怀疑你的工作问题不在于此。即你有你的Global.asax改变任何的JSON序列化的默认设置?

Can't pass ModelState validation in WebApi application for object which contains nullable types and has null values. The error message is "The value 'null' is not valid for DateProperty."

The code of object:

public class TestNull
{
    public int IntProperty { get; set; }
    public DateTime? DateProperty { get; set; }
}

Controller:

public class TestNullController : ApiController
{
    public TestNull Get(int id)
    {
        return new TestNull() { IntProperty = 1, DateProperty = null };
    }

    public HttpResponseMessage Put(int id, TestNull value)
    {
        if(ModelState.IsValid)
            return Request.CreateResponse(HttpStatusCode.OK, value);
        else
        {
            var errors = new Dictionary<string, IEnumerable<string>>();
            foreach (var keyValue in ModelState)
            {
                errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
        }
    }
}

Request:

$.getJSON("api/TestNull/1",
function (data) {
    console.log(data);
    $.ajax({
        url: "api/TestNull/" + data.IntProperty,
        type: 'PUT',
        datatype: 'json',
        data: data
    });
});

解决方案

I just did a quick test in one my own WebAPI projects and passing null as a value for a nullable value-type works fine. I suggest you inspect the actual data that is being send to your server using a tool like Fiddler

Two valid scenarios that will work are:

{ IntProperty: 1, DateProperty: null } 
{ IntProperty: 1 } // Yes, you can simply leave the property out

Scenarios that will NOT work are:

{ IntProperty: 1, DateProperty: "null" } // Notice the quotes
{ IntProperty: 1, DateProperty: undefined } // invalid JSON
{ IntProperty: 1, DateProperty: 0 } // Will not be properly interpreted by the .NET JSON Deserializer 

If the two default scenario's do not work then I suspect your problem lies elsewhere. I.e. Have you changed any of the default settings of the JSON serializer in your global.asax?

这篇关于ModelState中验证失败可空类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆