WebAPI calls a custom validation attribute twice on POST method call - normal?

917 views Asked by At

My issue: A custom validation attribute is called twice and not once when calling a webapi post method (with EF) - I am not sure if this is normal and would like a definitive answer. It validates at the following points:

  1. Just before the breakpoint enters the webapi application post method (presumably populating ModelState)

  2. Again just before the insert takes place (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; }
    
    }
    

Here is my webAPI end point:

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

Is the better solution simply to provide a Data Transfer class for application object with little/simple validation on it for the purposes of passing the data and then let any domain specific validation errors just bubble back via HttpResponseMessage therefore lookups are only run when the insert is attempted with reasonable data?

Thank you! Dan.

0

There are 0 answers