C# 检查剃刀页面中的登录用户角色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14969167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:35:56  来源:igfitidea点击:

Checking login user role in razor page

c#asp.netasp.net-mvcasp.net-mvc-3asp.net-mvc-4

提问by Asp Asp

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

我也发现那return View(user)不好,因为我不知道如何利用它user

采纳答案by Dave Alperovich

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

回答by Honorable Chow

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

戴夫的回答是正确的。我建议您考虑在模型上使用一个名为IsAdministratoror的属性CanSeeSidebar,并将回答该问题视为域逻辑

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.

视图应该只适用于模型。查看线程,从数据库中读取,在回答域问题方面是相同的。所有这些类型的问题都应该在您的控制器将模型交给视图之前回答。

回答by Ozan BAYRAM

For ASP.NET Core Razor Pages

对于 ASP.NET Core Razor 页面

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