Web API中的模型验证Model Validation

数据注释

在ASP.NET Web API中,您可以使用System.ComponentModel.DataAnnotations命名空间中的属性为模型上的属性设置验证规则。

using System.ComponentModel.DataAnnotations;

namespace MyApi.Models
{
    public class Product
    {
        [Required]
        [StringLength(50)]
        [Display(Name = "Last Name")]//该Display属性指定文本框的标题名称,而不是每个实例中的属性名称。
        public string LastName { get; set; }
        
        [StringLength(50,ErrorMessage = "First name cannot be longer than 50 characters.")]
        [Display(Name = "First Name")]
        public string FirstMidName { get; set; }

        //如果您将该DataType属性与日期字段一起使用,则还必须指定该DisplayFormat属性,
        //以确保该字段在Chrome浏览器中正确呈现。
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)]
        [Display(Name = "Enrollment Date")]
        public DateTime EnrollmentDate { get; set; }

        [Display(Name = "Full Name")]
        public string FullName
        {
            get
            {
                return LastName + "," + FirstMidName;
            }
        }
    }
}

处理验证错误:Handling Validation Errors

验证失败时,Web API不会自动向客户端返回错误。由控制器操作来检查模型状态并做出适当的响应。

您还可以创建操作筛选器以在调用控制器操作之前检查模型状态。以下代码显示了一个示例:

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;

namespace MyApi.Filters
{
    public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
    }
}

如果模型验证失败,则此过滤器返回包含验证错误的HTTP响应。在这种情况下,不会调用控制器操作。

如果模型验证失败,则此过滤器返回包含验证错误的HTTP响应。在这种情况下,不会调用控制器操作。

要将此过滤器应用于所有Web API控制器,请在配置期间将过滤器的实例添加到HttpConfiguration.Filters集合:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new ValidateModelAttribute());

        // ...
    }
}

另一种选择是将过滤器设置为各个控制器或控制器操作的属性:

public class ProductsController : ApiController
{
    [ValidateModel]
    public HttpResponseMessage Post(Product product)
    {
        // ...
    }
}

参阅:https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

原文地址:https://www.cnblogs.com/AndyChen2015/p/9603072.html