darrunategui
darrunategui

Reputation: 402

IControllerModelConvention with dependency injection

I am developing a website using asp.net core 2.0 MVC. I have come across a situation where I would like to apply different authorization filters to different controllers based on some logic. For example, all controllers starting with a prefix Identity would have one authorization filter run, while all other controllers would have another authorization filter run.

I followed this article showing that this can be done by adding an IControllerModelConvention implementation to the services.addMvc(options) method like below during startup in the ConfigureServices method.

services.AddMvc(options =>
{
    options.Conventions.Add(new MyAuthorizeFiltersControllerConvention());
    options.Filters.Add(typeof(MyOtherFilterThatShouldBeAppliedGlobally));
}

And here is the class MyAuthorizeFiltersControllerConvention where you can see I am adding a specifc authorize filter to every controller based on a naming convention.

public class AddAuthorizeFiltersControllerConvention : IControllerModelConvention
{
    public void Apply(ControllerModel controller)
    {
        if (controller.ControllerName.StartsWith("Identity"))
        {
            controller.Filters.Add(new AuthorizeFilter(...));

            // This doesn't work because controller.Filters 
            // is an IList<IFilterMetadata> rather than a FilterCollection
            controller.Filters.Add(typeof(AnotherFilter)); 
        }
        else
        {
            controller.Filters.Add(new AuthorizeFilter(...));
        }
    }
}

The problem I am having is I cannot add filters in this way using the typeof(filter) overload like I could during startup in the ConfigureServices method. I require this because some of the filters I want to add require dependency injection to instantiate them.

My question is how can I achieve this? Is it even possible?

Upvotes: 4

Views: 1974

Answers (1)

mbp
mbp

Reputation: 1273

This is how you can do it:

controller.Filters.Add(new TypeFilterAttribute(typeof(AnotherFilter)));

Upvotes: 5

Related Questions