"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Model Validation in ASP.NET Web API

by Mike Wasson

When a client sends data to your web API, often you want to validate the data before doing any processing. This article shows how to annotate your models, use the annotations for data validation, and handle validation errors in your web API.

Data Annotations

In ASP.NET Web API, you can use attributes from the System.ComponentModel.DataAnnotations namespace to set validation rules for properties on your model. Consider the following model:

[!code-csharpMain]

   1:  using System.ComponentModel.DataAnnotations;
   2:   
   3:  namespace MyApi.Models
   4:  {
   5:      public class Product
   6:      {
   7:          public int Id { get; set; }
   8:          [Required]
   9:          public string Name { get; set; }
  10:          public decimal Price { get; set; }
  11:          [Range(0, 999)]
  12:          public double Weight { get; set; }
  13:      }
  14:  }

If you have used model validation in ASP.NET MVC, this should look familiar. The Required attribute says that the Name property must not be null. The Range attribute says that Weight must be between zero and 999.

Suppose that a client sends a POST request with the following JSON representation:

[!code-jsonMain]

   1:  { "Id":4, "Price":2.99, "Weight":5 }

You can see that the client did not include the Name property, which is marked as required. When Web API converts the JSON into a Product instance, it validates the Product against the validation attributes. In your controller action, you can check whether the model is valid:

[!code-csharpMain]

   1:  using MyApi.Models;
   2:  using System.Net;
   3:  using System.Net.Http;
   4:  using System.Web.Http;
   5:   
   6:  namespace MyApi.Controllers
   7:  {
   8:      public class ProductsController : ApiController
   9:      {
  10:          public HttpResponseMessage Post(Product product)
  11:          {
  12:              if (ModelState.IsValid)
  13:              {
  14:                  // Do something with the product (not shown).
  15:   
  16:                  return new HttpResponseMessage(HttpStatusCode.OK);
  17:              }
  18:              else
  19:              {
  20:                  return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
  21:              }
  22:          }
  23:      }
  24:  }

Model validation does not guarantee that client data is safe. Additional validation might be needed in other layers of the application. (For example, the data layer might enforce foreign key constraints.) The tutorial Using Web API with Entity Framework explores some of these issues.

“Under-Posting”: Under-posting happens when the client leaves out some properties. For example, suppose the client sends the following:

[!code-jsonMain]

   1:  {"Id":4, "Name":"Gizmo"}

Here, the client did not specify values for Price or Weight. The JSON formatter assigns a default value of zero to the missing properties.

The model state is valid, because zero is a valid value for these properties. Whether this is a problem depends on your scenario. For example, in an update operation, you might want to distinguish between “zero” and “not set.” To force clients to set a value, make the property nullable and set the Required attribute:

[!code-csharpMain]

   1:  [Required]
   2:  public decimal? Price { get; set; }

“Over-Posting”: A client can also send more data than you expected. For example:

[!code-jsonMain]

   1:  {"Id":4, "Name":"Gizmo", "Color":"Blue"}

Here, the JSON includes a property (“Color”) that does not exist in the Product model. In this case, the JSON formatter simply ignores this value. (The XML formatter does the same.) Over-posting causes problems if your model has properties that you intended to be read-only. For example:

[!code-csharpMain]

   1:  public class UserProfile
   2:  {
   3:      public string Name { get; set; }
   4:      public Uri Blog { get; set; }
   5:      public bool IsAdmin { get; set; }  // uh-oh!
   6:  }

You don’t want users to update the IsAdmin property and elevate themselves to administrators! The safest strategy is to use a model class that exactly matches what the client is allowed to send:

[!code-csharpMain]

   1:  public class UserProfileDTO
   2:  {
   3:      public string Name { get; set; }
   4:      public Uri Blog { get; set; }
   5:      // Leave out "IsAdmin"
   6:  }

[!NOTE] Brad Wilson’s blog post “Input Validation vs. Model Validation in ASP.NET MVC” has a good discussion of under-posting and over-posting. Although the post is about ASP.NET MVC 2, the issues are still relevant to Web API.

Handling Validation Errors

Web API does not automatically return an error to the client when validation fails. It is up to the controller action to check the model state and respond appropriately.

You can also create an action filter to check the model state before the controller action is invoked. The following code shows an example:

[!code-csharpMain]

   1:  using System.Collections.Generic;
   2:  using System.Linq;
   3:  using System.Net;
   4:  using System.Net.Http;
   5:  using System.Web.Http.Controllers;
   6:  using System.Web.Http.Filters;
   7:  using System.Web.Http.ModelBinding;
   8:   
   9:  namespace MyApi.Filters
  10:  {
  11:      public class ValidateModelAttribute : ActionFilterAttribute
  12:      {
  13:          public override void OnActionExecuting(HttpActionContext actionContext)
  14:          {
  15:              if (actionContext.ModelState.IsValid == false)
  16:              {
  17:                  actionContext.Response = actionContext.Request.CreateErrorResponse(
  18:                      HttpStatusCode.BadRequest, actionContext.ModelState);
  19:              }
  20:          }
  21:      }
  22:  }

If model validation fails, this filter returns an HTTP response that contains the validation errors. In that case, the controller action is not invoked.

[!code-consoleMain]

   1:  HTTP/1.1 400 Bad Request
   2:  Content-Type: application/json; charset=utf-8
   3:  Date: Tue, 16 Jul 2013 21:02:29 GMT
   4:  Content-Length: 331
   5:   
   6:  {
   7:    "Message": "The request is invalid.",
   8:    "ModelState": {
   9:      "product": [
  10:        "Required property 'Name' not found in JSON. Path '', line 1, position 17."
  11:      ],
  12:      "product.Name": [
  13:        "The Name field is required."
  14:      ],
  15:      "product.Weight": [
  16:        "The field Weight must be between 0 and 999."
  17:      ]
  18:    }
  19:  }

To apply this filter to all Web API controllers, add an instance of the filter to the HttpConfiguration.Filters collection during configuration:

[!code-csharpMain]

   1:  public static class WebApiConfig
   2:  {
   3:      public static void Register(HttpConfiguration config)
   4:      {
   5:          config.Filters.Add(new ValidateModelAttribute());
   6:   
   7:          // ...
   8:      }
   9:  }

Another option is to set the filter as an attribute on individual controllers or controller actions:

[!code-csharpMain]

   1:  public class ProductsController : ApiController
   2:  {
   3:      [ValidateModel]
   4:      public HttpResponseMessage Post(Product product)
   5:      {
   6:          // ...
   7:      }
   8:  }



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api.htm
< THANKS ME>