默认格式化程序为servicestack时,Web Api中的ModelState验证

时间:2018-02-20 11:21:06

标签: c# asp.net-web-api serialization deserialization servicestack

我有WEB.API控制器使用属性进行模型状态验证,当我使用WEB API的默认序列化程序时,每件事情都可以正常工作,但是当我将它更改为servicestack所需的bool值属性和EnumDataType(typeof(VehicleType))时不行。我的意思是它表明模型状态是有效的,它不是,我这样配置servicestack: 在Owin创业公司:

private void ConfigureServicestack(HttpConfiguration config)
{
    config.Formatters.RemoveAt(0);
    config.Formatters.Insert(0, new ServiceStackTesxtFormatter());
}

和servicestack的这个类:

public class ServiceStackTextFormatter : MediaTypeFormatter
{
    public ServiceStackTextFormatter()
    {
        JsConfig.ConvertObjectTypesIntoStringDictionary = true;
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

        SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
        SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));
    }

    public override bool CanReadType(Type type)
    {
        if (type == null) throw new ArgumentNullException("type");
        return true;
    }

    public override bool CanWriteType(Type type)
    {
        if (type == null) throw new ArgumentNullException("type");
        return true;
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
    {
        var task = Task<object>.Factory.StartNew(() => JsonSerializer.DeserializeFromStream(type, readStream));
        return task;
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
    {
        var task = Task.Factory.StartNew(() => JsonSerializer.SerializeToStream(value, type, writeStream));
        return task;
    }
}

我的控制器输入是这样的:

        public class PostRequest 
    {

//this is custom attribute and works fine
        [Number]
        public string VehicleId{ get; set; }

//It works fine for string value
        [Required]
        public string CompanyWebSiteAddress{ get; set; }

//when I insert invalid vehicletype modelstate.isvalid is true

        [EnumDataType(typeof(VehicleType))]
        public VehicleType VehicleType{ get; set; }

//for this bool value when I dont send IsOwner modelstate.Isvalid is true also
        [Required]
        public bool IsOwner { get; set; }
}

奇怪的问题是,当我从应用程序启动中删除ConfigureServicestack时,每件事情都运行正常,我想也许如果其中一个属性为null或客户端servicestack没有提供它作为默认值将其淡化为例如IsOwner的设置如下: IsOwner“:false,但我不知道它是否正确或如何关闭此功能

1 个答案:

答案 0 :(得分:1)

我找到了答案,我不知道如果有更好的方法但是通过标记bool值可以为空它对bool值工作正常,这样:

public bool? IsOwner { get; set; }