asp.net _使用filter过滤器拦截

ActionFilterAttribute

FilterConfig可以添加过滤器,比如添加一个ActionFilterAttribute,每个页面的操作都会通过过滤器,可以用于一些场景,比如登录token验证,如果没有token或者token失效,就可以直接重定向到登录页面了,下面是简单的例子。
自定义一个ActionFilterAttribute:

namespace web.App_Start
{
 
    public class HandleTestAttribute: System.Web.Mvc.ActionFilterAttribute
    {
      
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            var controllerName = filterContext.RouteData.Values["controller"].ToString();
            var actionName = filterContext.RouteData.Values["action"].ToString();

            filterContext.HttpContext.Response.Write("结束时间:" + DateTime.Now.ToString() + "<br/>");
            filterContext.HttpContext.Response.Write("controller:" + controllerName + ",action:" + actionName);
        }
    }
}

在FilterConfig里添加这个HandleTestAttribute:

namespace web
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
           
            filters.Add(new HandleErrorAttribute());
            filters.Add(new HandleTestAttribute());
        
        }
    }


}

运行就可以看到,每页页面操作后,都写出过滤器写出的文字:
在这里插入图片描述

请求过滤,进行全局web api请求监听

有时候对所有请求进行过滤,比如添加一个全局的请求监听,然后记录日志。
需要在WebApiConfig中添加你自定义的拦截器:

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
            // 将 Web API 配置为仅使用不记名令牌身份验证。
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Filters.Add(new RequestHandler());
        }
    }

RequestHandler:


namespace web.App_Start
{
    public class RequestHandler: ActionFilterAttribute
    {
        public static readonly ILog loginfo = LogManager.GetLogger("loginfo");
       
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
           
            base.OnActionExecuting(filterContext);         
            loginfo.Info("收到请求了content:");

        }


    }
}

这样每次接收到api请求都能进行日志记录

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值