Web API 实战之 统一的请求验证

白话就不多说了,直接上代码:

筛选器部分:

using Ahoo.Demo.Message;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.Properties;

namespace Ahoo.Demo.WebAPI.Filter
{
    /// 
    /// 请求参数验证,统一处理筛选器
    /// 
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class ValidationMessageAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid)
            {
                ResponseMessage resp = new ResponseMessage
                {
                    IsSuccess = false,
                    ErrorCode = "0001",
                    Message = actionContext.ModelState.Values.First().Errors[0].ErrorMessage
                };
                actionContext.Response = actionContext.Request.CreateResponse(resp);
            }
            base.OnActionExecuting(actionContext);
        }
    }
}

使用部分:
在Global 注册请求筛选器:

GlobalConfiguration.Configuration.Filters.Add(new ValidationMessageAttribute());

你可能感兴趣的:(web-api)