我用Action拦截器主要处理接口验证信息,日志打印等功能
首先建立LoggerFilter,继承FilterAttribute, IActionFilter,并实现OnActionExecuting,OnActionExecuted方法
/// <summary>
/// action前执行校验
/// </summary>
/// <param name="filterContext"></param>
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
// 加密 验证
GCallBack gcb = new GCallBack();
try
{
_controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.Name;
HttpRequestBase request = filterContext.HttpContext.Request;
// 记录日志
LogHelper.WriteLog($"Controller\\{filterContext.ActionDescriptor.ActionName} ",
request.UserHostAddress + ":" + request.QueryString);
// 加密 验证
gcb = Validate(filterContext.HttpContext.Request);
// 验证失败
if (!string.IsNullOrEmpty(gcb.Message))
{
// 返回结果
filterContext.RequestContext.HttpContext.Response.Write(JsonHelper.ToJson(gcb));
//加了这句就不再走后面的Action
filterContext.Result = new HttpNotFoundResult();
}
}
catch (Exception e)
{
// 记录日志
LogHelper.WriteLog($"Controller\\{filterContext.ActionDescriptor.ActionName} ", "拦截异常", e.Message);
gcb.Message = "系统未知异常,请联系管理员";
// 返回结果
filterContext.RequestContext.HttpContext.Response.Write(JsonHelper.ToJson(gcb));
//加了这句就不再走后面的Action
filterContext.Result = new HttpNotFoundResult();
}
}
/// <summary>
/// action后执行方法
/// </summary>
/// <param name="filterContext"></param>
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
try
{
// 记录日志
LogHelper.WriteLog($"Controller\\{filterContext.ActionDescriptor.ActionName} ", "执行结束", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
catch (Exception e)
{
// 记录日志
LogHelper.WriteLog($"Controller\\{filterContext.ActionDescriptor.ActionName} ", "拦截异常", e.Message);
}
}
里面具体逻辑调用的方法就不写了,说明
// 返回结果
filterContext.RequestContext.HttpContext.Response.Write(JsonHelper.ToJson(gcb));
//加了这句就不再走后面的Action
filterContext.Result = new HttpNotFoundResult();
这两句是为了在验证不通过的时候直接跳转回画面,不在继续走后续接口,试过挺多方法,就这个成功了
调用:
/// <summary>
/// 获取城市列表
/// </summary>
/// <returns></returns>
[LoggerFilter]
public JsonResult GetCityList()
{
// 处理内容
}