Authorizable content with Razor

Easy way in 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.

Using it


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.

The code

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.