对未经身份验证的 ASP.NET MVC 请求运行授权筛选器和操作筛选器

发布于 2024-08-25 09:26:12 字数 327 浏览 10 评论 0原文

我用几个动作过滤器装饰了我的基本控制器。他们工作得很好。

其中一个过滤器设置请求 - 执行诸如根据域设置区域性等操作。

我还有一些需要使用 Authorize 属性进行授权的操作。

我的问题是,当用户尝试请求他们无权访问的页面时,授权过滤器就会启动并将他们重定向到一个页面,告诉他们无法查看该页面。

问题是操作过滤器永远不会运行,因此区域性和其他请求数据永远不会设置。这实际上会导致视图中的语言错误以及其他数据丢失。

我知道授权过滤器首先运行,但我的问题是:如何设计它,以便确保某些方法始终在返回视图之前运行,无论授权如何。

希望这是有道理的。

I have decorated my base controller with a couple of action filters. They work fine.

One of those filters sets up the request - does things like set the culture based on the domain, etc.

I also have a handful of actions that require authorization using the Authorize attribute.

My problem is that when an user attempts to request a page they are not authorized to access, the authorization filter kicks in and redirects them to a page telling them that they cannot vie the page.

The issue is that the action filters never run so the culture and other request data is never set. This effectively causes language to be wrong in the view and other data to be missing.

I know that authorization filters run first but my question is this: How can I design this such that I can ensure that certain methods are always run before the view is returned, regardless of the authorization.

Hope that makes sense.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无声静候 2024-09-01 09:26:12

根据此文档(在过滤器顺序标头),授权过滤器始终在操作过滤器之前运行。这意味着弄乱 Order 属性不会有帮助。

我认为处理此问题的最佳方法是编写自己的 Authorization 属性(通过子类化 AuthorizeAttribute 并覆盖 AuthorizeCore)并在授权失败时手动运行操作过滤器。

According to this documentation (under the Filter Order header), Authorization filters always run before Action filters. This means that messing with Order properties won't help.

I think the best way to handle this is to write your own Authorization attribute (by subclassing AuthorizeAttribute and overriding AuthorizeCore) and running your action filters manually when authorization fails.

梦与时光遇 2024-09-01 09:26:12

请参阅 MSDN 文章中的操作筛选器的执行顺序操作过滤器

基本上,您可以在这些区域性过滤器上提供 Order 属性,以便它在授权过滤器之前运行,如下所示:

[CultureRedirect(Order = 1)]
public class MyBaseController : Controller { }

[Authorize(Order = 2)]
public class RequiresAuth : MyBaseController { }

...

如果失败,您仍然可以在操作执行之前执行代码 在任何 ActionFilter 执行之前。

See Order of Execution for Action Filters on MSDN Article on Action Filter

Basically, you can supply an Order property on those culture filters so it runs before the Authorization filter, something like this:

[CultureRedirect(Order = 1)]
public class MyBaseController : Controller { }

[Authorize(Order = 2)]
public class RequiresAuth : MyBaseController { }

...

If that fails, you can still Execute code bfore an action executes and before any ActionFilter will executes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文