【问题标题】:Pass current user in ASP.NET MVC controller to DAL将 ASP.NET MVC 控制器中的当前用户传递给 DAL
【发布时间】:2018-01-25 02:04:13
【问题描述】:

我正在为我的 ASP.NET 应用程序使用 Windows 身份验证。在剃刀视图中获取当前用户名相当简单,即@User.Identity.Name

我正在实现的功能是在我的 sql 选择查询中传递当前用户名并从表中获取关联的角色。接下来,我想将角色传回控制器,以便我可以在所有应用程序视图中访问它。

这样我就可以在我的视图中执行操作,例如

@if (CurrentUserRole = "Admin") {
  // Do something
} else {
  // So something else
}

HomeController.cs

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using nmvs_db.dal;
using nmvs_module;
using nmvs_module.util;
using SecureMedi.Models;
using SecureMedi.DAL;

namespace SecureMedi.Controllers {
    public class HomeController: Controller {
        static HomeController() {
            foreach(string s in new string[] {
                "com.ibm.oauth.OAuthUtils",
                "nmvs_server",
                "nmvs_module"
            }) {
                var l = org.apache.log4j.Logger.getLogger(s);
                l.addAppender(new DotNetAppender());
                l.debug(s + " test");
            }
        }

        public IActionResult Error() {
            return View();
        }

        public IActionResult Index() {
            ViewData["TextAreaResult"] = "No result yet";
            return View();
        }

        public IActionResult AnotherPage() {
            ViewData["TextAreaResult"] = "No result yet";
            return View();
        }
    }
}

UsersDAL.cs (DAL)

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using SecureMedi.Models;

namespace SecureMedi.DAL {
    public class UsersDAL {
        public void CurrentUser(string currentUserName) {
            string connectionstring = "MY_CONNECTION_STRING";
            string sql = String.Format("select users.name 'Username', roles.name 'Role' from sys.database_principals users inner join sys.database_role_members memberof on users.principal_id = memberof.member_principal_id inner join sys.database_principals roles ON memberof.role_principal_id = roles.principal_id and roles.type = 'R' where users.name = '[{0}]'", currentUserName);
            SqlConnection conn = new SqlConnection(connectionstring);
            SqlCommand cmd = new SqlCommand(sql, conn);

            conn.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            if (rdr.Read()) {
                string CurrentUserRole = rdr["Role"].ToString();
                rdr.Close();
            }
            conn.Close();
        }
    }
}

对 DB 表运行查询直接返回类似

查询

select users.name 'Username', roles.name 'Role' from sys.database_principals users inner join sys.database_role_members memberof on users.principal_id = memberof.member_principal_id inner join sys.database_principals roles ON memberof.role_principal_id = roles.principal_id and roles.type = 'R' where users.name = 'Domain\username'

结果

Username             Role 
Domain\username      Admin

另外,我不能 100% 确定我是否在我的 CurrentUser 函数中正确传递了 currentUserName 参数。

我看过 How to get the current user in ASP.NET MVCHow to pass a value from ASP.NET MVC controller to ASP.NET webforms control inside MVC View? 但我不确定如何在我的控制器和 DAL 之间来回传递当前用户名的值。

【问题讨论】:

  • 让你的 CurrentUser 方法返回一个字符串,写 return CurrentUserRole; 似乎是一个明显的起点?然后您可以调用该方法,将 User.Identity.Name 作为当前用户名传入,然后取回当前角色。至于将 currentUserName arg 传递到数据库中,它并不理想,因为它容易受到 SQL 注入的影响。学习 ADO.NET 教程并了解如何使用参数。如果您愿意,请参阅bobby-tables.com,它有解释和一些示例。
  • 你的 CurrentUser 函数没有返回任何内容,并且你在 if 语句中声明了局部变量“CurrentUserRole”,它应该如何工作?此外,此方法不是静态的,因此您必须先创建 UsersDAL 类的实例才能调用它。

标签: c# asp.net asp.net-mvc razor


【解决方案1】:
public CurrentUser GetCurrentUser(string currentUserName) {
        string connectionstring = "MY_CONNECTION_STRING";
        string sql = String.Format("select users.name 'Username', roles.name 'Role' from sys.database_principals users inner join sys.database_role_members memberof on users.principal_id = memberof.member_principal_id inner join sys.database_principals roles ON memberof.role_principal_id = roles.principal_id and roles.type = 'R' where users.name = '[{0}]'", currentUserName);
        SqlConnection conn = new SqlConnection(connectionstring);
        SqlCommand cmd = new SqlCommand(sql, conn);

        conn.Open();
        CurrentUser currentUser = new CurrentUser();
        SqlDataReader rdr = cmd.ExecuteReader();
        if (rdr.Read()) {
            currentUser.Role = rdr["Role"].ToString();
            currentUser.Username = currentUserName;
            rdr.Close();
        }
        conn.Close();

       return currentUser;

    }


public class CurrentUser
{
    public string Username {get;set;}
    public string Role {get;set;}
 }

在控制器中:

public IActionResult Index() {
        UsersDal dal = new UsersDal();
        ViewData["CurrentUser"] = dal.GetCurrentUser("username");

        return View();
    }

在cshtml中:

@{
   var user = ViewData["CurrentUser"];
 }

 <b>@user.Username</b>

【讨论】:

  • 您能否进一步解释您的评论After ViewData["CurrentUser"] = new method and controller pass.
  • ViewData["CurrentUser"] =GetCurrentUser("hakan");
  • 首先创建实例UsersDAL.After: instance.GetCurrentUser("hakan")
  • 我的意思是如何将当前登录的用户名从控制器传递给 DAL 函数并将结果返回给 ViewData 中的控制器
  • 你可以使用这个>>> var currentUser = ViewData["CurrentUser"]; @currentUser.View 中的用户名(cshtml)
猜你喜欢
  • 1970-01-01
  • 2010-09-14
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多