Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Glenn 28 posts 101 karma points
    Jan 20, 2014 @ 06:02
    Glenn
    0

    Umbraco WebAPI and Model State

    Hi All,

    I have been pulling my hair out trying to get this one working. I am not to sure of the inheritance structure of UmbracoApiController, but I assume at some point it inherits from ApiController. I have created a Validation Filter attribute that will validate against the model state. I have added my model into the model folder and set the appropriate validation attributes on the model. However ModelState never seems to populate or contain my model.

    Any ideas?

    Here is my WebApi Class:

    public class LeadCaptureApiController : UmbracoApiController
    {
        [ValidateModelFilter]
        public HttpResponseMessage ProcessLead(NewLead newLead)
        {
            var results = Leads.Api.Leads.NewLead(newLead.Name, newLead.Email, newLead.PhoneNumber, newLead.State);
            return Request.CreateResponse(HttpStatusCode.Created, newLead);
        }
    }
    

    and here is my Filter Class:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
        public class ValidateModelFilterAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(HttpActionContext actionContext)
            {
                if (actionContext.ModelState.IsValid == false)
                {
                    actionContext.Response = actionContext.Request.CreateErrorResponse(
                     HttpStatusCode.BadRequest, actionContext.ModelState);
                }
            }
        }
    

    and finally my Model

    public class NewLead
    {
        [Required]
        [Display(Name = "Name")]
        public string Name { get; set; }
    
        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email")]
        public string Email { get; set; }
    
        [Required]
        [DataType(DataType.PhoneNumber)]
        [Display(Name = "Phone Number")]
        public string PhoneNumber { get; set; }
    
        [Required]
        [DataType(DataType.Text)]
        public string State { get; set; }
    }
    
  • Glenn 28 posts 101 karma points
    Jan 20, 2014 @ 06:43
    Glenn
    100

    Figured it out.. was actually working. But "DataType.EmailAddress" does not validate it as an email address. Not to sure about the what the attribute is for. Anyone know?

Please Sign in or register to post replies

Write your reply to:

Draft