Problems with Model binding and validation attributes with asp.net Web API

时光毁灭记忆、已成空白 提交于 2019-12-09 06:55:24

You need to inspect what is inside in the 500 internal server

  • make sure that you turn customerror off in your web.config
  • If you selfhost web.API you need to set GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
  • use your browser development console's network tab (in IE, Chrome you can get the console with F12) or if you are using FireFox then use FireBug or a thrid party tool like Fiddler.

Then you can see what went wrong on the server and go further to solve your problem.

In your case this is in the response:

"Message":"An error has occurred.","ExceptionMessage":"Property 'StartDate' on type 'MvcApplication3.Controllers.TaskViewModel' is invalid. Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)] to be recognized as required. Consider attributing the declaring type with [DataContract] and the property with [DataMember(IsRequired=true)].","ExceptionType":"System.InvalidOperationException"

So your problem is not that you have two attributes but that you've marked your properties with [Required] to solve this the exception tells you what to do.

You need to add [DataMember(IsRequired=true)] to your required properties where the property type is a value type (e.g int, datatime, etc.):

So change your TaskViewModel to:

[DataContract]
public class TaskViewModel
{

    //Default Constructor
    public TaskViewModel() { }

    [DataMember]
    public Guid TaskId { get; set; }

    [Required]
    [DataMember]
    [StringLength(10)]
    public string Description { get; set; }

    [Required]
    [DataMember(IsRequired = true)]
    [DataType(DataType.DateTime)]
    public System.DateTime StartDate { get; set; }

    [Required]
    [DataMember]
    public string Status { get; set; }

    [DataMember]
    public System.Guid ListID { get; set; }
}

Some side notes:

  • You need to reference the System.Runtime.Serialization dll in order to use the DataMemberAttribute
  • You need to mark your class with [DataContract] and you need to mark all of its properties with [DataMember] not just the required ones.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!