【发布时间】:2018-02-20 11:21:06
【问题描述】:
我有 WEB.API 控制器,它使用属性进行模型状态验证,当我使用 WEB API 的默认序列化程序时,一切正常,但是当我将它更改为 bool 值和 EnumDataType(typeof(VehicleType)) 的 servicestack 所需属性时不行。我的意思是它表明模型状态是有效的,但不是,我以这种方式配置了 servicestack: 在 Owin 启动中:
private void ConfigureServicestack(HttpConfiguration config)
{
config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, new ServiceStackTesxtFormatter());
}
还有这个用于服务堆栈的类:
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 时,一切正常,我想也许如果属性之一为空或客户端服务堆栈未提供,请将其淡化为默认值,例如 IsOwner 将其设置为:" IsOwner":false,但是不知道对不对或者怎么关闭这个功能
【问题讨论】:
标签: c# asp.net-web-api serialization deserialization servicestack