<del id="d4fwx"><form id="d4fwx"></form></del>
      <del id="d4fwx"><form id="d4fwx"></form></del><del id="d4fwx"><form id="d4fwx"></form></del>

            <code id="d4fwx"><abbr id="d4fwx"></abbr></code>
          • ASP.NETMVC中怎么驗證后臺參數(shù)-創(chuàng)新互聯(lián)

            今天就跟大家聊聊有關(guān)ASP.NET MVC中怎么驗證后臺參數(shù),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

            專注于為中小企業(yè)提供做網(wǎng)站、成都網(wǎng)站制作服務(wù),電腦端+手機端+微信端的三站合一,更高效的管理,為中小企業(yè)故城免費做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了千余家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實現(xiàn)規(guī)模擴充和轉(zhuǎn)變。

            一、通過 if-if 判斷 


            if(string.IsNullOrEmpty(info.UserName))
            
            {
            
              return FailJson("用戶名不能為空");
            
            }
            
            if(string.IsNullOrEmpty(info.Password))
            
            {
            
              return FailJson("用戶密碼不能為空")
            
            }

            逐個對參數(shù)進(jìn)行驗證,這種方式最粗暴,但當(dāng)時在WebForm下也確實這么用過。對于參數(shù)少的方法還好,如果參數(shù)一多,就要寫n多的if-if,相當(dāng)繁瑣,更重要的是這部分判斷沒法重用,另一個方法又是這樣判斷。

            二、通過 DataAnnotation

            mvc提供了DataAnnotation對Action的Model進(jìn)行驗證,說到底DataAnnotation就是一系列繼承了ValidationAttribute的特性,例如RangeAttribute,RequiredAttribute等等。ValidationAttribute 的虛方法IsValid 就是用來判斷被標(biāo)記的對象是否符合當(dāng)前規(guī)則。asp.net mvc在進(jìn)行model binding的時候,會通過反射,獲取標(biāo)記的ValidationAttribute,然后調(diào)用 IsValid 來判斷當(dāng)前參數(shù)是否符合規(guī)則,如果驗證不通過,還會收集錯誤信息,這也是為什么我們可以在Action里通過ModelState.IsValid判斷Model驗證是否通過,通過ModelState來獲取驗證失敗信息的原因。例如上面的例子:

            public class RegisterInfo
            
            {
            
              [Required(ErrorMessage="用戶名不能為空")]
            
              public string UserName{get;set;}
            
             [Required(ErrorMessage="密碼不能為空")]
            
              public string Password { get; set; }
            
            }

            事實上在webform上也可以參照mvc的實現(xiàn)原理實現(xiàn)這個過程。這種方式的優(yōu)點的實現(xiàn)起來非常優(yōu)雅,而且靈活,如果有多個Action共用一個Model參數(shù)的話,只要在一個地方寫就夠了,關(guān)鍵是它讓我們的代碼看起來非常簡潔。

            不過這種方式也有缺點,通常我們的項目可能會有很多的接口,比如幾十個接口,有些接口只有兩三個參數(shù),為每個接口定義一個類包裝參數(shù)有點奢侈,而且實際上為這個類命名也是非常頭疼的一件事。

            三、DataAnnotation 也可以標(biāo)記在參數(shù)上

            通過驗證特性的AttributeUsage可以看到,它不只可以標(biāo)記在屬性和字段上,也可以標(biāo)記在參數(shù)上。也就是說,我們也可以這樣寫:

            public ActionResult Register([Required(ErrorMessage="用戶名不能為空")]string userName, [Required(ErrorMessage="密碼不能為空")]string password)

            這樣寫也是ok的,不過很明顯,這樣寫很方法參數(shù)會難看,特別是在有多個參數(shù),或者參數(shù)有多種驗證規(guī)則的時候。

            四、自定義ValidateAttribute

            我們知道可以利用過濾器在mvc的Action執(zhí)行前做一些處理,例如身份驗證,授權(quán)處理的。同理,這里也可以用來對參數(shù)進(jìn)行驗證。FilterAttribute是一個常見的過濾器,它允許我們在Action執(zhí)行前后做一些操作,這里我們要做的就是在Action前驗證參數(shù),如果驗證不通過,就不再執(zhí)行下去了。

            定義一個BaseValidateAttribute基類如下:

            public class BaseValidateAttribute : FilterAttribute
            
            {
            
              protected virtual void HandleError(ActionExecutingContext context)
            
              {
            
                for (int i = ValidateHandlerProviders.Handlers.Count; i > 0; i--)
            
                {
            
                  ValidateHandlerProviders.Handlers[i - 1].Handle(context);
            
                  if (context.Result != null)
            
                  {
            
                    break;
            
                  }
            
                }
            
              }
            
            }

            HandleError 用于在驗證失敗時處理結(jié)果,這里ValidateHandlerProviders提過IValidateHandler用于處理結(jié)果,它可以在外部進(jìn)行注冊。IValidateHandler定義如下:

            public interface IValidateHandler
            
            {
            
              void Handle(ActionExecutingContext context);
            
            }

            ValidateHandlerProviders定義如下,它有一個默認(rèn)的處理器。

            public class ValidateHandlerProviders
            
            {
            
              public static List<IValidateHandler> Handlers { get; private set; }
            
             
            
              static ValidateHandlerProviders()
            
              {
            
                Handlers = new List<IValidateHandler>()
            
                {
            
                  new DefaultValidateHandler()
            
                };
            
              }
            
             
            
              public static void Register(IValidateHandler handler)
            
              {
            
                Handlers.Add(handler);
            
              }
            
            }  

            這樣做的目的是,由于我們可能有很多具體的ValidateAttribute,可以把這模塊獨立開來,而把最終的處理過程交給外部決定,例如我們在項目中可以定義一個處理器:

            public class StanderValidateHandler : IValidateHandler
            
            {
            
              public void Handle(ActionExecutingContext filterContext)
            
              {
            
                filterContext.Result = new StanderJsonResult()
            
                {
            
                  Result = FastStatnderResult.Fail("參數(shù)驗證失敗", 555)
            
                };
            
              }
            
            }

            然后再應(yīng)用程序啟動時注冊:ValidateHandlerProviders.Handlers.Add(new StanderValidateHandler());

            舉個兩個栗子:

            ValidateNullttribute:

            public class ValidateNullAttribute : BaseValidateAttribute, IActionFilter
            
            {
            
              public bool ValidateEmpty { get; set; }
            
             
            
              public string Parameter { get; set; }
            
             
            
              public ValidateNullAttribute(string parameter, bool validateEmpty = false)
            
              {
            
                ValidateEmpty = validateEmpty;
            
                Parameter = parameter;
            
              }
            
             
            
              public void OnActionExecuting(ActionExecutingContext filterContext)
            
              {
            
                string[] validates = Parameter.Split(',');
            
                foreach (var p in validates)
            
                {
            
                  string value = filterContext.HttpContext.Request[p];
            
                  if(ValidateEmpty)
            
                  {
            
                    if (string.IsNullOrEmpty(value))
            
                    {
            
                      base.HandleError(filterContext);
            
                    }
            
                  }
            
                  else
            
                  {
            
                    if (value == null)
            
                    {
            
                      base.HandleError(filterContext);
            
                    }
            
                  }
            
                }
            
              }
            
             
            
              public void OnActionExecuted(ActionExecutedContext filterContext)
            
              {
            
             
            
              }
            
            }

            ValidateRegexAttribute:

             public class ValidateRegexAttribute : BaseValidateAttribute, IActionFilter
            
            {
            
              private Regex _regex;
            
             
            
              public string Pattern { get; set; }
            
             
            
              public string Parameter { get; set; }
            
             
            
              public ValidateRegexAttribute(string parameter, string pattern)
            
              {
            
                _regex = new Regex(pattern);
            
                Parameter = parameter;
            
              }
            
             
            
              public void OnActionExecuting(ActionExecutingContext filterContext)
            
              {
            
                string[] validates = Parameter.Split(',');
            
                foreach (var p in validates)
            
                {
            
                  string value = filterContext.HttpContext.Request[p];
            
                  if (!_regex.IsMatch(value))
            
                  {
            
                    base.HandleError(filterContext);
            
                  }
            
                }
            
              }
            
              public void OnActionExecuted(ActionExecutedContext filterContext)
            
              { 
            
              }
            
            }

            更多的驗證同理實現(xiàn)即可。

            這樣,我們上面的寫法就變成:

            [ValidateNull("userName,password")]
            
            public ActionResult Register(string userName, string password)

            綜合看起來,還是ok的,與上面的DataAnnotation可以權(quán)衡選擇使用,這里我們可以擴展更多有用的信息,如錯誤描述等等。

            看完上述內(nèi)容,你們對ASP.NET MVC中怎么驗證后臺參數(shù)有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

            分享題目:ASP.NETMVC中怎么驗證后臺參數(shù)-創(chuàng)新互聯(lián)
            標(biāo)題URL:http://www.jbt999.com/article4/eooie.html

            成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機、用戶體驗外貿(mào)建站、App開發(fā)、網(wǎng)站排名、關(guān)鍵詞優(yōu)化

            廣告

            聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:[email protected]。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

            成都網(wǎng)頁設(shè)計公司

              <del id="d4fwx"><form id="d4fwx"></form></del>
              <del id="d4fwx"><form id="d4fwx"></form></del><del id="d4fwx"><form id="d4fwx"></form></del>

                    <code id="d4fwx"><abbr id="d4fwx"></abbr></code>
                  • 无码日 | 欧美日韩中文字幕无码 | 青娱乐在线精品视频 | 亚洲视频网站免费观看 | 性交在线观看视频网站 |