1. 程式人生 > >Web API 實戰之 統一的請求驗證

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 { /// <summary> /// 請求引數驗證,統一處理篩選器 /// </summary> [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<ResponseMessage>(resp); } base.OnActionExecuting(actionContext); } } }

使用部分:
在Global 註冊請求篩選器:

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