首页 新闻 会员 周边

关于.net core 拦截器的问题,求各位大大指点一下。

0
悬赏园豆:10 [待解决问题]

在asp.net core 1.1中,我有一个全局的拦截器,但是我所有的action中 有几个不需要这个拦截器拦截,我以前在asp.net mvc4中的做法是 再定义一个attribute  加在那几个action上边,在 全局的拦截器里判断 代码如下

public partial class CustActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Object[] actionFilter = filterContext.ActionDescriptor.GetCustomAttributes(
                typeof(NoActionFilterAttribute), false);
            //有 NoAuthentication 则 不验证
            if (actionFilter.Length > 0)
            {
                base.OnActionExecuting(filterContext);
                return;
            }
}
}

但是现在 在asp.net core1.1 中 context.
ActionDescriptor没有
GetCustomAttributes这个方法了,求大大们指点一下,应该怎么做!

srymbud的主页 srymbud | 初学一级 | 园豆:4
提问于:2017-05-26 15:51
< >
分享
所有回答(2)
0

你不应该这样做的,

你可以在这个拦截器上定义一个属性啊

比如是否拦截

public bool IsFiltger{get;set;}

OnActionExecuting代码中判断IsFiltger,如果IsFiltger是true的话就做,如果不是的话你就不需要做任何处理。、

然后在action上加上特性CustActionFilter(IsFilter=false)。

或者在构造函数中传入是否拦截也一样。

Emrys5 | 园豆:223 (菜鸟二级) | 2017-05-26 16:49

现在一个比较困扰我的问题是  在asp.net core 的OnActionExecuting  我不知道怎么才能去到 自定义的 特性。

支持(0) 反对(0) srymbud | 园豆:4 (初学一级) | 2017-05-26 16:53

@srymbud: 

如果是你说的需求。用我刚才说的就可以了。

如果你非要在这里获取自定义特性,如果官方没有提供,你就用反射自己获取好来。

因为在这里你应该可以获取到Controller和action就是类名和方法名,肯定也可以获取到类上或者方法上的特性了。

 

支持(0) 反对(0) Emrys5 | 园豆:223 (菜鸟二级) | 2017-05-26 16:56
0

这是asp.net core 2.1代码,1.1也是一样的
public override void OnActionExecuting(ActionExecutingContext context)
{
AuthoritybtnAttribute authoritybtnAttribute =(AuthoritybtnAttribute)((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).MethodInfo.GetCustomAttribute(typeof(AuthoritybtnAttribute), false);

}

码农精神之怪咖 | 园豆:202 (菜鸟二级) | 2018-09-02 12:55

赞,学到了。
现在没有GetCustomAttribute,只有GetCustomAttributes

AuthoritybtnAttribute authoritybtnAttribute =(AuthoritybtnAttribute)((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).MethodInfo.GetCustomAttributes(typeof(AuthoritybtnAttribute), false)[0];

支持(0) 反对(0) b4b4 | 园豆:202 (菜鸟二级) | 2019-09-12 10:18
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册