using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Mvc;

namespace JMB.Web
{
    public class ParameterValidationActionFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //var param  =  filterContext.RequestContext.HttpContext.Request.Params;
            var paramss = filterContext.ActionParameters;
            if (paramss != null && paramss.Count > 0)
            {
                foreach (var para in paramss)
                {
                    var formCollection = para.Value as FormCollection;
                    if (formCollection != null) //是否是post请求
                    {
                        var keys = formCollection.AllKeys;
                        if (keys != null && keys.Count() > 0)
                        {
                            //获取所有参数
                            foreach (var item in keys)
                            {
                                var result = formCollection.GetValue(item).AttemptedValue ?? "";
                                // TO DO

                            }

                        }

                    }
                    else //get请求
                    {
                        if (para.Value != null)
                        {
                            //这个也有能是 (string str1,string str2)格式的话就是获取每个参数
                            // 如果是 (QueryModel model) 的话 就是QueryModel对象
                            var result = para.Value?.ToString() ?? "";

                            
                        }

                    }
                }

            }

           
        }

    }
}

然后在web网站下的App_Start文件夹FilterConfig类里添加ParameterValidationActionFilter 过滤器

using System.Web.Mvc;

namespace JMB.Web
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new ParameterValidationActionFilter());
        }
    }
}

 

posted on 2021-03-29 17:39  青春似雨后霓虹  阅读(1311)  评论(0编辑  收藏  举报