Easy way in Asp.net MVC with Razor, to solve this problem:
â€œIâ€™ve a piece of code in the view, but I want to render it, just if youâ€™re part of a particular role.â€
Lucky us, with razor and his mechanism to easily extends Html Helpers, we can allow that some part of the code required authorization. Letâ€™s see an example of how to get there.
The html text will be render only if youâ€™re part of the role Administrator. In this example weâ€™re using just one role: Administrator, you can enumerate more than one role separated by comma, have a look in the source we are using params.
This method, as every html helpers existent in the world, is part of a static class.
Looking for more? Sorry for disappoint you!
This kind of authorization requires that youâ€™ll set properly the authorization on server side, this means, i.e. if you hide a link on the client-side, you also have to set the Authorize attribute on your controller action to avoid security leaks.