从 ASP.NET MVC 站点中的 ResultExecutingContext 访问控制器方法
我正在编写一个属性,我想在其中访问在其操作之一上具有该属性的控制器所派生的类上的方法。这实在是太拗口了,所以让我解释一下:
- 我的控制器派生自一个类,该类具有具有以下签名的方法:
protected bool IsSearchEngine()
(基类本身派生自Controller)
- 我的控制器上的操作之一有一个属性
- 该属性派生自
ActionFilterAttribute
并重载OnResultExecuting
。 OnResultExecuting
方法有一个ResultExecutingContext
参数。
如何通过 ResultExecutingContext
访问 IsSearchEngine()
?
更新: 到目前为止,我已经获得了编译器和 Intellisense 接受这一点:
(filterContext.Controller as MyAssembly.Controllers.BaseControllerClass).IsSearchEngine()
这是正确的方法吗?我还没有测试过。
I'm writing an attribute where I want to access a method on the class that the controller that has the attribute on one of its actions derives from. That's quite a mouthful, so let me explain:
- My controller derives from a class that has a method with the following signature:
protected bool IsSearchEngine()
(the base class itself derives fromController
) - One of the actions on my controller has an attribute
- The attribute derives from
ActionFilterAttribute
and overloadsOnResultExecuting
. - The
OnResultExecuting
method has aResultExecutingContext
parameter.
How can I access IsSearchEngine()
through the ResultExecutingContext
?
UPDATE: So far, I've gotten the compiler and Intellisense to accept this:
(filterContext.Controller as MyAssembly.Controllers.BaseControllerClass).IsSearchEngine()
Is that the right way to do this? I haven't tested it yet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过将
resultExecutingContext.Controller
转换为BaseController
,您可以访问基本控制器的所有属性和方法,但方法IsSearchEngine()
的保护级别代码> 您无法访问它。如果您通过public
声明了IsSerchEngine()
,则可以将其调用为((BaseController)resultExecutingContext.Controller).IsSearchEngine()
By casting the
resultExecutingContext.Controller
toBaseController
you can access through all Property and Methods of your base controller, but the protection level of your MethodIsSearchEngine()
you cannot access it. If you declared yourIsSerchEngine()
bypublic
you can just call it as((BaseController)resultExecutingContext.Controller).IsSearchEngine()