asp.net mvc – How to check current user role on Site.Master page? – Education Career Blog

I need to write a menu in Site.Master where certain menu items have to be visible or not depending on current user role. How can I check that from the page?
Usually would just write the logic in a controller, but the Site.Master doesn’t have one (in my project at least!). I’d appreciate any pointers.

,

Use HttpContext.Current.User.

That would always be visible from your views / partial views / master pages.

For example, to display different html for a given role, say, MyRole, you would simply write:

<% if(HttpContext.Current.User.IsInRole("MyRole")) { %>

    // tags for MyRole

<% } else { %>

    // tags for other users

<%} %>

This is fine as it is “display logic” which belongs in the View (or master page), as opposed to “application logic” which belongs in the controller.

Note that views are just templates. You can write code into them without messing the neat MVC pattern, so long as it is display logic only.

A view or a master page don’t “have a controller”. They are just templates that the controller can find and use.

Leave a Comment