Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 4.0 WebAPI在POST方法调用时调用自定义验证属性两次-正常?_C# 4.0_Asp.net Mvc 4_Asp.net Web Api_Validationattribute - Fatal编程技术网

C# 4.0 WebAPI在POST方法调用时调用自定义验证属性两次-正常?

C# 4.0 WebAPI在POST方法调用时调用自定义验证属性两次-正常?,c#-4.0,asp.net-mvc-4,asp.net-web-api,validationattribute,C# 4.0,Asp.net Mvc 4,Asp.net Web Api,Validationattribute,我的问题: 在调用webapi post方法(使用EF)时,自定义验证属性会被调用两次,而不是一次-我不确定这是否正常,希望得到一个明确的答案。它在以下几点进行验证: 在断点进入webapi应用程序post方法之前(可能是填充ModelState) 再次在插入之前(db.Applications.Add(application)) 更好的解决方案是简单地为应用程序对象提供一个数据传输类,并对其进行少量/简单的验证,以便传递数据,然后让任何特定于域的验证错误通过HttpResponseMessag

我的问题: 在调用webapi post方法(使用EF)时,自定义验证属性会被调用两次,而不是一次-我不确定这是否正常,希望得到一个明确的答案。它在以下几点进行验证:

  • 在断点进入webapi应用程序post方法之前(可能是填充ModelState)

  • 再次在插入之前(db.Applications.Add(application))

    更好的解决方案是简单地为应用程序对象提供一个数据传输类,并对其进行少量/简单的验证,以便传递数据,然后让任何特定于域的验证错误通过HttpResponseMessage返回,因此,只有在尝试使用合理的数据插入时才运行查找吗

    谢谢大家!! 丹

    [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; }
    
    }
    
    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);
        }
    }