本文介绍了使用模型绑定和验证问题asp.net的Web API属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写与的ASP.NET Web API上的Web API,并利用下面的视图模型。
我似乎有与数据绑定的问题时,有一个特定的属性两个验证属性(即[要求]和[StringLength(10)])。
在发布来自客户端的JSON值到窗体的控制器动作:
// POST API /列表
公共无效后([FromBody] TaskViewModel taskVM)
我注意以下事项:
- 如果我删除了多重属性之一,一切束缚OK;
- 如果我在多个属性离开时,客户端临危500内部服务器错误,永远达不到邮政法的主体。
任何想法,为什么出现这种情况?
干杯
公共类TaskViewModel
{ //默认的构造函数
公共TaskViewModel(){}
公共静态TaskViewModel MakeTaskViewModel(任务任务)
{
返回新TaskViewModel(任务);
} //构造
私人TaskViewModel(任务任务)
{
this.TaskId = task.TaskID;
this.Description = task.Description;
this.StartDate = task.StartDate;
this.Status = task.Status;
this.ListID = task.ListID;
} 公众的Guid TASKID {搞定;组; } [需要]
[StringLength(10)]
公共字符串描述{搞定;组; } [需要]
[数据类型(DataType.DateTime)
公共System.DateTime的起始日期{搞定;组; } [需要]
公共字符串状态{搞定;组; } 公众的System.Guid ListID {搞定;组; }
}
解决方案
您需要检查的是在500内部服务器内部
- 请确保您打开关闭在你的web.config
- 如果您selfhost web.API你需要设置
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
- 使用浏览器的开发控制台的网络选项卡(IE,Chrome浏览器就可以得到与F12控制台),或者如果您使用的是Firefox,然后使用萤火或THRID第三方工具一样的。
这时你可以看到什么地方出了错在服务器上,并进一步去解决你的问题。
在你的情况,这是在响应:
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.
这篇关于使用模型绑定和验证问题asp.net的Web API属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!