How to associate an attribute with an action filter using Autofac?

I have a custom authorization filter that has constructor dependent dependencies.

public class CustomAuthorizationFilter : IAuthorizationFilter 

And a common attribute that just stores data.

 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class CustomAuthorizeAttribute : FilterAttribute 

The approach that I "borrowed" from here , and I really like the separation. I understand how the filter goes and “gets” the attribute, but I'm missing something with the connection.

How do I bind an attribute to a filter so that the filter is called when there is an attribute? Ninject has syntax for this , But I did not compute the equivalent in Autofac

If this is what I need to configure in an application outside Autofac, that's fine too.

Thanks! Josh

+4
source share
1 answer

You can use the same class as the filter and attribute. But you can also define another attribute and check if it has been defined.

Then you should register your filter / attribute class: inside Global.asax , just like filters.Add(new HandleErrorAttribute()); .

Inside the filterMethods method (in your case it should be OnAuthorize), you can check if there is any other IsDefined attribute or if some property is defined.

+1
source

Source: https://habr.com/ru/post/1387415/


All Articles