我在web api中设置boolean的默认值时遇到问题。
我有以下实现
模型
public class StatusModel
{
[Range(1, long.MaxValue, ErrorMessage = "Id is invalid or is not sent.")]
[RegularExpression(@"^[a-zA-Z0-9'' ']+$", ErrorMessage = "Special character should not be entered")]
public long Id { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "IsActive is invalid or is not sent.")]
[Range(0 , 1 , ErrorMessage="IsActive Is Sent In Value 0 or 1 Only")]
public bool? IsActive { get; set; }
}
控制器
[HttpPut]
public string Activate([FromBody] StatusModel model)
{
// implementation goes here
}
WebApi.Config
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// To register exception logger of IQueryable exceptions
config.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// JSON
config.Formatters.Remove(config.Formatters.XmlFormatter);
//to convert date time to local
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
// JSON formatter
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
}
}
问题是每次我尝试向我的服务发送布尔值时,值会让人感到困惑,例如
如果我发送以下Json Is Active
值设置为true
{ " Id":4, " IsActive":5 }
如果我发送以下Json,则出现以下错误IsActive is invalid or is not sent
,这是正确的
{ " Id":4, " IsActive":" 0" }