简体   繁体   中英

Pass current user in ASP.NET MVC controller to DAL

I am using windows authentication for my ASP.NET application. Fetching the current user name is fairly straightforward in razor views ie @User.Identity.Name

The feature I am implementing is that I pass the current user name in my sql select query and get the associated role from the table. Next, I would like to pass the role back to the controller so that I can access it in all of my application views.

So that I could perform operations in my views like

@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();
        }
    }
}

Running a query against DB table directly returns something like

Query

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'

Result

Username             Role 
Domain\username      Admin

Also, I am not 100% sure if I am passing the currentUserName arg correctly in my CurrentUser function.

I have looked up on How to get the current user in ASP.NET MVC and How to pass a value from ASP.NET MVC controller to ASP.NET webforms control inside MVC View? but I am not sure how to pass the value of current user name to and fro from my controller and DAL.

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

in controller :

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

        return View();
    }

in cshtml:

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

 <b>@user.Username</b>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM