Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking login user role in razor page

@if (Request.IsAuthenticated && User.Identity.Name=="administrator") {      <div id="sidebar">         <div class="module">         <ul class="menu">                             <li>@Html.ActionLink("Home", "Index", "Home")</li>                             <li>@Html.ActionLink("About", "About", "Home")</li>                             <li>@Html.ActionLink("Contact", "Contact", "Home")</li>                         </ul>          </div>          <div class="mainContent">              Hello, @User.Identity.Name !          </div>      </div> 

This is my layout if the user is authenticated as administrator but this sort of check looks no good, I need to check the role of the user not his name.

Here is the controler method

    public ActionResult AuthenticatedUserLayout(string username)      {         var lst=userContext.UserProfiles.ToList();         var user = lst.Select(u => u.UserName == username);          if(IsAdmin(Session["LoginUser"].ToString())) return View(user); else return Index();     } 

I also find that return View(user) is no good, because I don't know how to make any use of that user.

like image 478
Asp Asp Avatar asked Feb 19 '13 22:02

Asp Asp


People also ask

How do you get a role from Claimsprincipal?

So to get all roles of the user you need to get roles from all identities. This is what the built-in ClaimPrincipal. IsInRole(string roleName) method does i.e. it checks the given roleName exists in any of the identities. Also, note the use of claim type set in the identity Identity.

What is @model in razor page?

It is a self-contained class that represents the data and behaviour of a specific "view" or page. The view model pattern is used extensively in MVC application development, where it mainly represents data, but typically little behaviour. In Razor Pages, the PageModel is also the view model.


1 Answers

@if (Request.IsAuthenticated && User.IsInRole("Administrators")) {      <div id="sidebar">         <div class="module">            <ul class="menu">               <li>@Html.ActionLink("Home", "Index", "Home")</li>               <li>@Html.ActionLink("About", "About", "Home")</li>               <li>@Html.ActionLink("Contact", "Contact", "Home")</li>             </ul>          </div>          <div class="mainContent">              Hello, @User.Identity.Name !          </div>      </div> } 
like image 136
Dave Alperovich Avatar answered Sep 29 '22 03:09

Dave Alperovich