在所有的控制器动作强制行为过滤器(C#/ ASP.NET MVC)

编程入门 行业动态 更新时间:2024-10-09 10:26:08
本文介绍了在所有的控制器动作强制行为过滤器(C#/ ASP.NET MVC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我做了一个新的动作过滤器(属性,类似于[授权])的授权访问基于会话值控制器动作。不过,我基本上装饰与属性的(除了极少数例外),我所有的控制器动作。

I made a new action filter (attribute, similar to [Authorize]) which authorizes access to a controller action based on a session value. However, I'm basically decorating all my controller actions with that attribute (with the exception of very few).

所以,我认为这将是最好有一个行为过滤器的总是的执行的情况除外的,其中附上一份[ExemptFromAuthorize]属性到一个控制器行动? (也许通过继承我自己的Controller类?)

So, I thought it would be better to have that Action Filter always executed except in cases where I attach an [ExemptFromAuthorize] attribute to a controller action? (Maybe via inheriting to my own Controller class?)

我怎样才能做到这一点?

How can I do this?

推荐答案

与运行jeef3's答案,我想出了这个。它可以使用更多的错误检查和鲁棒性像多分隔措施,但总的思想工作。

Running with jeef3's answer, I came up with this. It could use more error checking and robustness like multiple delimited actions, but the general idea works.

在特定的情况下,可以测试会话值,并决定返回了授权也。

In your specific case, you could test for the session value and decide to return out of the authorization also.

public class AuthorizeWithExemptionsAttribute : AuthorizeAttribute { public string Exemption { get; set; } public override void OnAuthorization(AuthorizationContext filterContext) { if (filterContext.RouteData.GetRequiredString("action") == Exemption) return; base.OnAuthorization(filterContext); } }

用法:

[AuthorizeWithExemptions(Roles="admin", ExemptAction="Index")] public class AdminController : Controller ...

更多推荐

在所有的控制器动作强制行为过滤器(C#/ ASP.NET MVC)

本文发布于:2023-11-17 11:09:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609821.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:过滤器   控制器   动作   MVC   ASP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!