1、开局一张图
2、 要实现这种效果其实简单,我们只需要重写 ActionFilterAttribute即可。
public class ReActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
base.OnActionExecuted(context);
}
public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
foreach (var item in context.ActionArguments)
{
var obj = item.Value;
var type = obj.GetType();
if (type.BaseType.Name.Equals("Object"))
{
if (IsExistSpecialChar(type, obj, out string fieldName))
{
context.HttpContext.Response.StatusCode = 501;
context.HttpContext.Response.ContentType = "application/json;charset=utf-8";
context.Result = new JsonResult(new ApiResultModel("501", $"请求失败!{fieldName}包含特殊字符。", null, false));
return Task.CompletedTask;
}
}
}
return base.OnActionExecutionAsync(context, next);
}
private bool IsExistSpecialChar(Type type, object obj, out string fieldNam)
{
var proper = type.GetProperties();
fieldNam = string.Empty;
var flag = false;
foreach (var item in proper)
{
if (!string.IsNullOrWhiteSpace(item.PropertyType.Name) && item.PropertyType.Name.Equals("String"))
{
var val = item.GetValue(obj, null);
if (StringHelper.IsExistSQLChar(val.ToStr()))
{
fieldNam = item.Name;
flag = true;
}
}
else if (!string.IsNullOrWhiteSpace(item.PropertyType.Name) && item.PropertyType.Name.Contains("Dictionary"))
{
var dictionary = item.GetValue(obj, null) as System.Collections.IDictionary;
foreach (var val in dictionary.Values)
{
if (!string.IsNullOrWhiteSpace(val.GetType().Name) && val.GetType().Name.Equals("String"))
{
if (StringHelper.IsExistSQLChar(val.ToStr()))
{
fieldNam = item.Name;
flag = true;
}
}
else if (!string.IsNullOrWhiteSpace(val.GetType().BaseType.Name) && val.GetType().BaseType.Name.Equals("Object"))
{
flag = IsExistSpecialChar(val.GetType(), val, out fieldNam);
}
if (flag)
{
return flag;
}
}
}
else if (!string.IsNullOrWhiteSpace(item.PropertyType.BaseType.Name) && item.PropertyType.BaseType.Name.Equals("Object"))
{
flag = IsExistSpecialChar(item.PropertyType, item.GetValue(obj, null), out fieldNam);
}
if(flag)
{
return flag;
}
}
return flag;
}
}