Copied to clipboard

Flag this post as spam?

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


  • Sonja 132 posts 620 karma points
    Nov 01, 2018 @ 07:53
    Sonja
    0

    Umbraco web api validation doesn't work

    Hi I'm using umbraco web api. I have a model

    public class MyModel
    {
    public string Name1 { get; set; }
    [Required]
    [Range(1,12, ErrorMessage ="Invalid Month")]
    public int myMonth { get; set; }
    [Required]
    [Range(00, 99, ErrorMessage = "Invalid Year")]
    public int myYear { get; set; }
    }
    

    and in the controller

    [HttpPost]
            public HttpResponseMessage TestMyModel(HttpRequestMessage request)
            {
                var msg = new HttpResponseMessage();
                XmlSerializer deserializer = new XmlSerializer(typeof(MyModel));
                try
                {
                    var reader = new StringReader(request.Content.ReadAsStringAsync().Result);
                    var mymodel = (MyModel)deserializer.Deserialize(reader);
    
                    if (ModelState.IsValid)
                    {
                        msg.StatusCode = HttpStatusCode.OK;
                    }
                    else
                    {
                        msg.StatusCode = HttpStatusCode.BadRequest;
                    }
                }
                catch (Exception exc)
                {
                    msg.StatusCode = HttpStatusCode.BadRequest;
                }
                return msg;
            }
    

    And none of the validation is working. Please advice

  • Alex Skrypnyk 5908 posts 22603 karma points MVP 4x admin c-trib
    Nov 01, 2018 @ 12:05
    Alex Skrypnyk
    0

    Hi Sonja

    The validation works only if you pass this param to the method, instead of "HttpRequestMessage request" use "MyModel model" then validation will work

    Alex

  • Sonja 132 posts 620 karma points
    Nov 05, 2018 @ 04:55
    Sonja
    101

    Thanks but when I was passing MyModel instead of HttpRequestMessage I was getting null in the request.

    I've managed to solve the problem, I put

    Validate<MyModel>(myModel);   
     if (ModelState.IsValid)
     { 
                msg.StatusCode = HttpStatusCode.OK;
     }
    else
     {
               msg.StatusCode = HttpStatusCode.BadRequest;
     }
    
  • Alex Skrypnyk 5908 posts 22603 karma points MVP 4x admin c-trib
    Nov 05, 2018 @ 08:53
    Alex Skrypnyk
    0

    Hello Sonja

    Thanks for sharing! Have a great day!

    Alex

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies