【ASP.NET Web API教程】6.4 模型验证

本文是Web API系列教程的第6.4小节

6.4 Model Validation
6.4 模型验证


By Mike Wasson|July 20, 2012
作者:Mike Wasson | 2012-6-20

When a client sends data to your web API, often you want to validate the data before doing any processing.
当客户端发送数据给你的Web API时,你通常希望在做其它处理之前先对数据进行验证。

6.4.1 Data Annotations
6.4.1 数据注解

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:
在ASP.NET Web API中,你可以使用System.ComponentModel.DataAnnotations命名空间的注解属性来设置模型属性的验证规则。考虑以下模型:

public class Product
    public int Id { get; set; }
[Required] public string Name { get; set; } public decimal Price { get; set; }
[Range(0,999)] public double Weight { get; set; } }

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.
如果你曾在ASP.NET MVC中使用过模型验证,这看上去是类似的。Required注解属性说明Name属性必须不为空。Range注解属性说明Weight必须在0-999之间。

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

{ "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:
你可以看出,客户端并未包含被标记成required的Name属性。当Web API将该JSON转换成Product实例时,它会根据这些验证注解属性对Product进行验证。在控制器动作中,你可以检查该模型是否有效:

public class ProductsController : ApiController
    public HttpResponseMessage Post(Product product)
        if (ModelState.IsValid)
            // Do something with the product (not shown).
            // 用product做一些事(未表示出来)
return new HttpResponseMessage(HttpStatusCode.OK); } else { return new HttpResponseMessage(HttpStatusCode.BadRequest); } } }

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.
模型验证并不保证客户端数据是安全的。在应用程序的其它层面可能会需要附加验证(例如,数据层可能会强制外键约束)。“Using Web API with Entity Framework(与Entity Framework一起使用Web API)(本系列教程的第2章)”教程考察一些此类问题。

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

{"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:

public decimal? Price { get; set; }

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

{"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:

public class UserProfile
    public string Name { get; set; }
    public Uri Blog { get; set; }
    public bool IsAdmin { get; set; }  // uh-oh!(啊哦!)

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:

public class UserProfileDTO
    public string Name { get; set; }
    public Uri Blog { get; set; }
    // Leave out "IsAdmin"
    // 略去了"IsAdmin"

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.
Brad Wilson的博客文档“Input Validation vs. Model Validation in ASP.NET MVC(ASP.NET MVC中的输入验证与模型验证)”对under-posting和over-posting有很好的讨论。虽然这篇博文是关于ASP.NET MVC 2的,但这种问题仍然关系到Web API。

6.4.2 Handling Validation Errors
6.4.2 处理验证错误

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.
当验证失败时,Web API并不会自动地将错误返回给客户端。这取决于控制器动作对模型状态及响应进行适当的检查。

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

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;
public class ModelValidationFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (actionContext.ModelState.IsValid == false) { // Return the validation errors in the response body. // 在响应体中返回验证错误 var errors = new Dictionary<string, IEnumerable<string>>(); foreach (KeyValuePair<string, ModelState> keyValue in actionContext.ModelState) { errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage); }
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors); } } }

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

HTTP/1.1 400 Bad Request
Server: ASP.NET Development Server/
Date: Fri, 20 Jul 2012 21:42:18 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 239
Connection: Close
{ "product": [ "Required property 'Name' not found in JSON. Line 1, position 18." ],
"product.Name": [ "The Name field is required." ],
"product.Weight": [ "The field Weight must be between 0 and 999." ] }

If you are using the latest Web API source on CodePlex, you can use the HttpError class to return validation errors to the client. The HttpError class is not available in the RC release.
如果你正在使用CodePlex上最新版的Web API,可以使用HttpError类将验证错误返回给客户端。HttpError类在RC版(指Web API的预览版)中无效。

You can apply this filter globally to all Web API controllers. In the Application_Start method, add the filter to the HttpConfiguration.Filters collection:
你可以将此过滤器全局性地运用于所有Web API控制器。在Application_Start方法中,将此过滤器添加到HttpConfiguration.Filters集合:

protected void Application_Start()
    // ...
GlobalConfiguration.Configuration.Filters.Add(new ModelValidationFilterAttribute()); }

Alternatively, you can apply it to individual controllers or controller actions, by adding the filter as an attribute:

public class ProductsController : ApiController
    public HttpResponseMessage Post(Product product)
        // ...


posted @ 2013-07-16 12:30  r01cn  阅读(8773)  评论(14编辑  收藏  举报