【问题标题】:Using impersonation for checking user in Razor Pages在 Razor 页面中使用模拟检查用户
【发布时间】:2020-07-12 10:42:08
【问题描述】:

我有一个用 asp.net 编写的 web 应用程序,我通过这个简单的代码检查了用户名:

            string[] userName = Context.Request.ServerVariables["LOGON_USER"].Split('\\');
            try {
                LabelUserName.Text = userName[1];
                LabelUserName.Visible = true;
                HiddenField1.Value = userName[1];
                ViewState["UserName"] = userName[1];
            }
            catch (Exception error)
            {
                System.Diagnostics.Debug.WriteLine("Cannot impersonate user: " + error.ToString());
                LabelUserName.Text = "UNKNOWN";
                LabelUserName.Visible = true;
                
            }

我尝试使用具有最新 .net 核心的 Razor Pages 重写此 Web 应用程序,但我有点困惑:

  1. 如何在 _Layout 中添加此代码(这是我的假设 - 之前此代码在 MasterPage 中 - 它对所有页面都是全局的 - 或者可能有其他方法?)?
  2. 也许是获得此功能的更好方法?我需要为用户查看应用程序获取 Windows 登录信息。

【问题讨论】:

  • 你在.net core中使用的是razor page还是mvc?
  • 我正在使用 Razor 页面

标签: c# asp.net razor-pages impersonation


【解决方案1】:

公共代码将被移动到一个基类(剃须刀页面的情况下是basepagemodel),basepagemodel 类应该从 PageModel 继承,如下所示:

public class BasePageModel : PageModel
{
     public bool UserInfo
    {
        get
        {
            // play with httprequest and extract user login name, accesstoken, etc and perform validation according to your requirement
            return !string.IsNullOrEmpty(HttpContext.Request.Cookies["accesstoken"]);
        }
    }
    
    // another method
}

public class indexModel : BasePageModel
{
        // request handling here
}

将basepagemodel设置为共享布局页面(_Layout)的模型如下:

@model Application.BasePageModel
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=EDGE" />
<title>@ViewData["Title"]</title>
<environment include="Development,Production">
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/lib/jquery-ui/dist/css/jquery-ui.css" />
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
</environment>
</head>
<body>
 <div>
        <a>
             <strong>
               @{
                  <span style="margin-right:-2px;">Welcome</span>
                  if (Model.UserInfo)
                       {
                           <span>User Logged in</span>
                       }
                    }
              </strong>
         </a>
  </div>
 </body>
</html>

【讨论】:

  • 我应该自己创建吗?我找到了一些文档并使用 _ViewStart.cshtml 作为这类事情的基础。
猜你喜欢
  • 2018-11-26
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
  • 2021-11-11
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多