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

简介: 原文:【ASP.NET Web API教程】6.4 模型验证本文是Web API系列教程的第6.4小节 6.4 Model Validation 6.4 模型验证 摘自:http://www.asp.
原文: 【ASP.NET Web API教程】6.4 模型验证

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

6.4 Model Validation
6.4 模型验证

摘自:http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

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:
假设客户端发送了一个带有下列JSON表示的POST请求:

{ "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:
Under-Posting(递交不足)”:当客户端遗漏了某些属性时,便会发生“Under-posting”。例如,假设客户端发送如下:

{"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.
此处,客户端并未指定Price或Weight的值。JSON格式化器会将默认值(这里是零)赋给这些缺失的属性。

图6.4-1

图6.4-1

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:
此时模型的状态是有效的,因为零是这些属性的有效值。这是否是一个问题取决于你所处的场景。例如,在一个更新操作中,你可能希望区分出“零”与“未设置”。为了强迫客户端要设置一个值,将该属性构造成nullable(可空的),并设置Required注解属性:

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

"Over-Posting": A client can also send more data than you expected. For example:
Over-Posting(过份递交)”:客户端也可能发送比期望还多的数据。例如:

{"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:
此处,JSON包含了Product模型中存在的属性(“Color”)。在这种情况下,JSON格式化器会简单地忽略该值(XML格式化器却不同)。若你的模型具有只读属性,Over-posting会产生问题。例如:

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:
如果你不想让用户对IsAdmin属性进行更新,并将其提升给管理员。最安全的策略是使用一个与允许客户端发送严格匹配的模型类:

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响应。在此情况下,不会调用控制器动作。

HTTP/1.1 400 Bad Request
Server: ASP.NET Development Server/10.0.0.0
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
{
    [ModelValidationFilter]
    public HttpResponseMessage Post(Product product)
    {
        // ...
    }
}

看完此文如果觉得有所收获,请给个推荐
你的推荐是我继续下去的动力,也会让更多人关注并获益,这也是你的贡献。

目录
相关文章
|
11月前
|
人工智能 数据可视化 测试技术
Postman 性能测试教程:快速上手 API 压测
本文介绍API上线后因高频调用导致服务器告警,通过Postman与Apifox进行压力测试排查性能瓶颈。对比两款工具在批量请求、断言验证、可视化报告等方面的优劣,探讨API性能优化策略及行业未来发展方向。
Postman 性能测试教程:快速上手 API 压测
|
JSON 监控 网络协议
干货分享“对接的 API 总是不稳定,网络分层模型” 看电商 API 故障的本质
本文从 OSI 七层网络模型出发,深入剖析电商 API 不稳定的根本原因,涵盖物理层到应用层的典型故障与解决方案,结合阿里、京东等大厂架构,详解如何构建高稳定性的电商 API 通信体系。
|
JSON 监控 API
在线网络PING接口检测服务器连通状态免费API教程
接口盒子提供免费PING检测API,可测试域名或IP的连通性与响应速度,支持指定地域节点,适用于服务器运维和网络监控。
2163 0
|
JSON API PHP
通用图片搜索API:百度源免费接口教程
本文介绍一款基于百度图片搜索的免费API接口,由接口盒子提供。支持关键词搜索,具备详细请求与返回参数说明,并提供PHP及Python调用示例。开发者可快速集成实现图片搜索功能,适用于内容聚合、素材库建设等场景。
2145 0
|
JSON 机器人 API
随机昵称网名API接口教程:轻松获取百万创意昵称库
接口盒子提供随机昵称网名API,拥有百万级中文昵称库,支持聊天机器人、游戏角色等场景的昵称生成。提供详细调用指南及多语言示例代码,助力开发者高效集成。
1029 0
|
11月前
|
人工智能 API 开发者
图文教程:阿里云百炼API-KEY获取方法,亲测全流程
本文详细介绍了如何获取阿里云百炼API-KEY,包含完整流程与截图指引。需先开通百炼平台及大模型服务,再通过控制台创建并复制API-KEY。目前平台提供千万tokens免费额度,适合开发者快速上手使用。
7009 5
|
11月前
|
JSON API 调度
Midjourney 技术拆解与阿里云开发者实战指南:从扩散模型到 API 批量生成
Midjourney深度解析:基于优化Stable Diffusion,实现文本到图像高效生成。涵盖技术架构、扩散模型原理、API调用、批量生成系统及阿里云生态协同,助力开发者快速落地AIGC图像创作。
1277 0
|
11月前
|
人工智能 API 监控
告别多接口拼凑!阿里云 API 模型聚合实现技术能力协同跃迁
API聚合整合400+国内外AI模型,统一接口、屏蔽差异,降低开发与维护成本,提升效率与系统稳定性,助力开发者高效应对多API调用困境。
1161 0
|
11月前
|
人工智能 前端开发 测试技术
Kimi K2 模型更新,带来更强的代码能力、更快的 API
今天,Kimi K2 模型的最新版本 0905 开源发布,进一步提升其在真实编程任务中的表现
1963 0
本地用阿里云API调用的r1模型,返回的think字段中有奇怪的东西,并且停止思考
这两张图片展示了模型生成内容时可能出现的异常情况,包括图像模糊、结构错误或不符合预期的结果。这可能是由于模型训练数据不足、输入指令不清晰或模型本身存在局限性所致。建议优化输入提示词或调整模型参数以提升输出质量。