views:

39

answers:

2

I have

public class FundController 
{
    private Site _site;
    public ViewResult Fund()
    {
    }
}

I'd like to add an Action Filter to this Fund method:

public class FundController 
{
    private Site _site;

    [MyFilter]
    public ViewResult Fund()
    {
    }
}

but the Action Filter needs access to _site. Is this possible? If so, how?

+3  A: 

Expose the field in a public property, then cast the controller in the filter to FundController.

For example:

FundController controller = (FundController)filterContext.Controller;

Site site = controller.Site;
SLaks
This would work better if you used an interface for the property.E.g., ISiteController.Instead of casting to the concrete type, your filter can cast to the interface type. This would allow you to reuse the filter on other controllers.
Chris McKenzie
@Chris: It would work better with dependency injection for the ActionFilter.
SLaks
A: 

You could also setup your ActionFilter with a Required Parameter that you then pass in the site

[MyFilter(_site)]
public ViewResult Fund() {
}
Brad C.
This cannot work. Attribute parameters must be compile-time constants.
SLaks