Action Filter是否可以访问Controller中的私有对象?

Dav*_*Dev 1 c# asp.net-mvc action-filter

我有

public class FundController 
{
    private Site _site;
    public ViewResult Fund()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

我想在此基金方法中添加一个动作过滤器:

public class FundController 
{
    private Site _site;

    [MyFilter]
    public ViewResult Fund()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

但是Action Filter需要访问权限_site.这可能吗?如果是这样,怎么样?

SLa*_*aks 6

将该字段公开在公共属性中,然后将过滤器中的控制器转换为FundController.

例如:

FundController controller = (FundController)filterContext.Controller;

Site site = controller.Site;
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用属性的接口,这将更好地工作.例如,ISiteController.您的过滤器可以转换为接口类型,而不是转换为具体类型.这将允许您在其他控制器上重用过滤器. (3认同)