gpt4 book ai didi

c# - MVC 中的 ActionFilter 和 Authorize 属性导致对象引用错误

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:17 24 4
gpt4 key购买 nike

我正在使用 MVC4 构建 ASP.NET 应用程序。我在我的业务逻辑中使用了 ActionFilterAttributeAuthorizeAttribute。以下是示例代码

Controller 类

[SessionExpire]
[AuthorizeSubscription]
public class StoreController : Controller
{
public ActionResult StoreDetail()
{
// My logic goes here
}

[AuthorizeProductEdit]
[HttpGet]
public ActionResult EditProduct()
{
// My logic goes here
}

如果我们看代码,我首先使用了继承 ActionFilterAttribute 类的 SessionExpire 属性,它检查 session 是否对当前有效请求并在那里做一些重定向。接下来,我正在检查继承 AuthorizeAttribute 类的 AuthorizeSubscription 属性。它还会根据那里编写的逻辑进行一些重定向。

EditProduct 操作中,我使用了另一个 AuthorizeAttribute

如果我点击了 StoreDetail 操作的 url 而没有进行任何 session,它会将我重定向到所需的页面。

但是如果我点击 EditProduct 操作的 url,它会抛出 对象引用错误。在调试过程中,它首先进入 AuthorizeProdcutEdit 的代码,并且找不到 Session Null。

为什么它不首先执行 SessionExpire 代码,如果发现 Session Null 则退出?

最佳答案

根据 MSDN :

Filters run in the following order:

  1. Authorization filters
  2. Action filters
  3. Response filters
  4. Exception filters

SessionExpire 属性在 AuthorizeSubscription 属性之后触发的原因是因为 MVC 总是首先触发授权过滤器。

因此,要解决该问题,您需要使用 SessionExpire 来实现 IAuthorizationFilter(并且可能继承 Attribute)。

此外,您还需要 set the order of your attributes ,因为 .NET 框架不保证它们的处理顺序。

[SessionExpire(Order=1)]
[AuthorizeSubscription(Order=2)]
public class StoreController : Controller
{
// Remaining implementation...

请注意,最好的方法是 separate your filters from your attributes ,这既允许它们对 DI 友好,也允许您通过以特定顺序全局注册过滤器来明确设置顺序。

关于c# - MVC 中的 ActionFilter 和 Authorize 属性导致对象引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35453485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com