Asp.net webapi 判斷請求參數是否為空簡易方法 Model Validation 判斷請求參數是否為空


通常情況下,對於那些經常為別人提供數據接口的開發人員來說,對於調用方傳遞過來的參數都會有驗證處理。例如:

if (string.IsNullOrEmpty(entity.Name))
{
    //當姓名為空時,.........
}
if (entity.Age<0 || entity.Age>100)
{
    //當年齡小於0或大於100時,有的人可能超過一百歲,我希望我的有生之年Age>100,emm,.........
}
 
if (string.IsNullOrEmpty(entity.PhoneNum))
{
    //當電話號碼為空時,.........
}
if (!string.IsNullOrEmpty(entity.PhoneNum))
{
    Regex regex = new Regex("^1[34578]\\d{9}$");
    var result=regex.IsMatch(entity.PhoneNum);
    if (!result)
    {
        //當電話號碼格式不合法時,.........
 
    }
}
//以下還有50個字段需要驗證,是不是有種絕望的感覺,有木有?有木有?有人可能會跟調用者說,某個字段必須怎么怎么樣,有些人就喜歡故意傳錯,故意刁鑽,到頭來,最苦逼的還是寫接口的人。

有時候一個系統有十幾二個接口,光驗證的代碼就一大堆,真的有時候不想寫,都說程序猿是最聰明的一批人,自然有好的解決方法。

  C# webapi 有一種叫模型驗證的東西,在java里面,應該有一種注解的東西可以處理。

  在ASP.NET Web API中,你可以使用System.ComponentModel.DataAnnotations命名空間的注解屬性來設置模型屬性的驗證規則。考慮以下模型:

public class Personnel
    {
        [Required(ErrorMessage = "Name參數不能為空")]//Required 驗證這個參數不能為空 ErrorMessage:為空時自定義錯誤信息
        public string Name { get; set; }
 
        [Range(1,100, ErrorMessage="Age參數只能是大於1,小於100")]//Range 驗證值只能在某些范圍內,只適用於Int類型的字段
        public int Age { get; set; }
 
        [Required(ErrorMessage = "電話號不能為空")]
        [RegularExpression("^[1]+[3,4,5,7,8]+\\d{9}", ErrorMessage = "PhoneNum不合法的電話號碼格式")]//RegularExpression 用正則驗證字段的合法性,多用於身份證、電話號碼、郵箱、等等...
        public string PhoneNum { get; set; }
    }

這樣的話就可以節省大量冗余代碼,那么,接下來如何去處理呢?

 在接口請求之前,我們可以對客戶端傳過來的數據進行模型驗證處理,對於webapi比較熟悉的人應該知道過濾器,不知道的可以看我前面的文章,如何使用webapi三大過濾器,過濾器是基於AOP,面向切面的編程思想。

 在這里我們用的ActionFilterAttribute過濾器,只要繼承這個接口並且實現其中的OnActionExecuting方法就行。具體實現如下:

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 Huajie.Application.Web.Controllers.Apis
{
    public class ModeActionFilter: ActionFilterAttribute
    {
        /// <summary>
        /// 接口請求前驗證數據
        /// </summary>
        /// <param name="actionContext">上下文</param>
        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, new
                {
                    code= HttpStatusCode.BadRequest,//返回客戶端的狀態碼
                    success = false,
                    error = errors//顯示驗證錯誤的信息
                });
            }
        }
    }
}

在WebApiConfig.cs里面注冊一下這個過濾器

config.Filters.Add(new ModeActionFilter());

請求方法示例:

[Route("test")]
[HttpPost]
public string Test([FromBody] Personnel entity )
{
    return "成功!";
}

 自定義返回 (返回請求成功HttpStatusCode.OK 並且有多個錯誤 取第一個即可

actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, new ResultStr()
                {
                    content = null,
                    isSuccess = false,
                    message = actionContext.ModelState.FirstOrDefault().Value.Errors.FirstOrDefault().ErrorMessage
                });

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM