Is it possible to insert parameters in Filters Attributes?

Asked

Viewed 77 times

2

I use ASP.NET and to do the access control by level, I use a filter that checks the level of permission of the user and allows access to view.

[HttpPost]
[AutorizacaoFilterAttribute] //Esse filtro analisa a permissão do usuário
public ActionResult GetEmailAnalisysData()
{

}

But inside the Filter and I need to make one switch for each view that I add the [AutorizacaoFilterAttribute] and it ends up being exhausting, plus I’ll forget to add in either.

The question is: It is possible to pass parameters through filter? example:

[HttpPost]
[AutorizacaoFilterAttribute(1)] //1 significa o nível necessário para esse filter, assim eu me livro de precisar fazer um switch comparando o nome de cada view
public ActionResult GetEmailAnalisysData()
{

}

1 answer

3


In yours you can do as you like, but if you’re going to use the AuthorizationFilterAttribute which is the pattern of framework, there is no way to put arguments.

You can create your own by inheriting the AuthorizationFilterAttribute, then you can add a constructor with the parameter you want. But framework will not respect this, it will be necessary to create the logic of control, perhaps creating a Controller own as well. Including because that level would have to be sent somehow to compare with that argument. I don’t know how it does without the attribute.

Another possibility is to have different actions for each level.

  • I solved using the inheritance of AuthorizationFilterAttribute, I added a variable called Level and now I can pass this value in specific in each View: [AutorizacaoFilterAttribute(Level = 10)] . Thank you;

  • So you inherited like I said?

  • Yes ! now instead of using a heap of variables that received the name of the View and as value the necessary level, I just insert the annotation of the filter on top of it passing the level of it, inside the filter I check: Level >= Level (which was passed via attribute),if he allows it, otherwise he sends it to the login page. It made me save about 20 lines (because I made the case for each view of my site).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.