1

I have created a class CustomAuthorizeAttribute:AuthorizeAttribute for authorization, but I am unable to authorize in the razor view like @if(User.IsInRole("some role"));, but what I want is @if(CustomAuthorizeAttribute(My Parameters)) for my authorization.

How to do that?

polemon
  • 4,722
  • 3
  • 37
  • 48

1 Answers1

0

AuthorizeAttribute works by placing it on an action method, a controller, or as a global filter. It is not possible to use MVC filters inside of views (or at least not without a lot of work).

I suggest you ask a different question and narrow it to your requirements. There must be some reason why you are attempting this, but it is impossible to work out what you need to do (or if there is a much simpler approach) from your question.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • Tell me the possible way because i want to try this first else i will find some other solution – Rushi Mahindrakar Jul 11 '16 at 05:58
  • The [AuthorizeAttributeAclModule](https://github.com/maartenba/MvcSiteMapProvider/blob/master/src/MvcSiteMapProvider/MvcSiteMapProvider/Security/AuthorizeAttributeAclModule.cs) of `MvcSiteMapProvider` loads the `AuthorizeAttribute` from an action method to determine whether the user is authorized. It is unclear why you would want to create an attribute on the fly in your view to do the same, so I cannot tell you what direction to take exactly, only give you an example of how much code it takes to get there. – NightOwl888 Jul 11 '16 at 08:51
  • Say there are three users admin, employee and site user. All have access rights to some controllers index method and employee has all rights except edit and read only can just read the data, so i want to check the user rights and accordingly i want to load the edit and delete button for the user in my mvc razor view – Rushi Mahindrakar Jul 11 '16 at 08:56
  • So why not just put `if (User.IsInRole("edit"))` around the code that produces the button, making each "right" a role? If that does not suffice or is not maintainable enough for your business logic, I suggest you factor the business logic out into its own service that can be used both by your custom `AuthorizeAttribute` *and* by your action method, a custom HTML helper or child action to control visibility of the buttons. You can inject the service into your custom authorize attribute if you make it into a global filter as in [this example](http://stackoverflow.com/a/32254851/181087). – NightOwl888 Jul 11 '16 at 10:35