我的问题:在调用 webapi post 方法(使用 EF)时,自定义验证属性被调用了两次,而不是一次 - 我不确定这是否正常并且想要一个明确的答案。它在以下几点进行验证:
就在断点进入webapi应用post方法之前(推测是填充了ModelState)
再次在插入发生之前 (db.Applications.Add(application))
[Table("Applications")] public class Application { /// <summary> /// ApplicationID (auto-increment) /// </summary> [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int ApplicationID { get; set; } /// <summary> /// Name of the application /// </summary> [Required] [MaxLength(255)] public string ApplicationName { get; set; } /// <summary> /// Application ref (for friendly lookups) /// </summary> [Required] [MaxLength(150)] [UniqueApplicationReference] // <<<<<<< My custom validation attribute public string ApplicationRef { get; set; } /// <summary> /// Application status /// </summary> [Required] public bool? ApplicationStatus { get; set; } public virtual ICollection<ApplicationFeature> ApplicationFeatures { get; set; } }
这是我的 webAPI 端点:
public HttpResponseMessage PostApplication(Application application)
{
if (ModelState.IsValid)
{
db.Applications.Add(application);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, application);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = application.ApplicationID }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
更好的解决方案是简单地为应用程序对象提供一个数据传输类,对其进行很少/简单的验证,以便传递数据,然后让任何特定于域的验证错误通过 HttpResponseMessage 冒泡,因此查找仅在插入时运行尝试使用合理的数据?
谢谢!担。