TheProgrammer
TheProgrammer

Reputation: 1344

Validating HttpRequestMessage body

I have a web api and I wanted to validate the request coming in.

Currently I have this in my web api controller:

public HttpResponseMessage GetSomething([FromBody]SomeObject request)
{
    var test= request.Number;
    //omit
}

public class SomeObject
{
    [JsonProperty]
    public double Number {get;set;}
}

Currently if I send in a request and set Number equal to a string or a non double, when the request comes to the server the Number is just set to zero. How should I validate the request when it comes in because I don' want it to be zero when it comes in?

Upvotes: 0

Views: 5211

Answers (2)

Kirk Patrick Brown
Kirk Patrick Brown

Reputation: 184

This can be reused in all controllers by annotating it method with this filter.

[Valid] //here  we apply the filter and request made to this model is validated by validation rules on the model
[HttpPost]
 public HttpResponseMessage someMethod(SomeValidationModel someValidationModel)
 {
    //some logic
 }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace mynamespace.filters
{
    public class ValidAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {

            if (!actionContext.ModelState.IsValid)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
    }
}

Upvotes: 0

CodeNotFound
CodeNotFound

Reputation: 23220

To get an error and return to the user you can do check ModelState property of your controller API.

public IHttpActionResult Post([FromBody]SomeObject value)
{
    if(this.ModelState.IsValid)
    {
        // If you enter here all data are set correctly
        return Ok();
    }
    else
    {
        // here you use BadRequest method and pass the ModelState property.
        return this.BadRequest(this.ModelState);
    }
}

There is nothing to do, change in your Number property. The only modification I do is to change the return type of your action by using IHttpActionResult.

When the data set for Number if incorrect you will something like that on the client site:

{
    "Message": "The request is invalid.",
    "ModelState": {
        "value.number": [
            "Error converting value \"dfsdf\" to type 'System.Double'. Path 'number', line 2, position 19."
        ]
    }
}

Upvotes: 3

Related Questions