Checking login user role in razor page

C#asp.netasp.net Mvcasp.net Mvc-3asp.net Mvc-4

C# Problem Overview


@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.

C# Solutions


Solution 1 - C#

@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>
}

Solution 2 - C#

For ASP.NET Core Razor Pages

if (User.Identity.IsAuthenticated && User.IsInRole("Administrator"))

Solution 3 - C#

Dave's answer is correct. I would suggest that you consider using a property on your model called IsAdministrator or CanSeeSidebar and treat answering that question as domain logic.

The view should work only with the model. Looking at the thread, reading from a database, are the same in respect that they answer domain questions. All those types of questions should be answered before your controller hands the model off to the view.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAsp AspView Question on Stackoverflow
Solution 1 - C#Dave AlperovichView Answer on Stackoverflow
Solution 2 - C#Ozan BAYRAMView Answer on Stackoverflow
Solution 3 - C#Honorable ChowView Answer on Stackoverflow