首页 > 解决方案 > 如何在 C# 中构造一个方法以获取登录的用户名、查询 Active Directory 并返回用户的全名

问题描述

我想学习在 C# 中制作和使用方法。

我知道如何获取当前登录的 Windows 用户的用户名。而且我知道如何查询 Active Directory 以获取他们的全名。但是,我想制作一个可重用的方法,可以根据需要放入其他 Web 应用程序中。

有人会告诉我应该或可能如何构建吗?

我只是在 VB.Net 中这样做了,我可能在 C# 的某个地方有这个版本:

Protected Sub PopulateReviewerDDL()
    'Currently logged in user:  
    iUserName = Right(Request.ServerVariables("AUTH_USER"), (Request.ServerVariables("AUTH_USER").Length - 6)) 'Remove Domain name and backslash.

    Dim DBConn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
    Dim DBCmd As New SqlCommand("SELECTADISNames", DBConn)
    DBCmd.CommandType = Data.CommandType.StoredProcedure

    Try
        DBConn.Open()
        DBCmd.Parameters.Add("@LogonName", SqlDbType.VarChar).Value = iUserName

        Dim dr As SqlDataReader = DBCmd.ExecuteReader
        dr.Read()

        varLastName = dr("LastName").ToString
        varFirstName = dr("FirstName").ToString
        dr.Close()
        ReviewerName = varFirstName & " " & varLastName
        lblUserName.Text = ReviewerName

        If Not ddlReviewerName.Items.FindByText(ReviewerName) Is Nothing Then
            ddlReviewerName.Text = ReviewerName
        Else
            Response.Redirect("NoAccess.htm", False)
        End If

    Catch exp As Exception
        Response.Write(exp.Message)
    End Try
    'Close Database connection 
    DBCmd.Dispose()
    DBConn.Close()
    DBConn = Nothing
End Sub

公共部分类_默认:System.Web.UI.Page {

protected string ClearDomain(string sItem)
{
    int sLoc = (sItem.IndexOf("\\") + 1);
    string sOutPut;
    sOutPut = sItem.Substring(sLoc);
    return sOutPut;
}

protected void Page_Load(object sender, EventArgs e)
{

    string usr;
    usr = ClearDomain(User.Identity.Name.ToString());
    string dpt;
    dpt = "";

    SqlConnection DBConn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    SqlCommand DBCmd = new SqlCommand("SELECTADISNames", DBConn);
    DBCmd.CommandType = System.Data.CommandType.StoredProcedure;

    try
    {
        DBConn.Open();
        DBCmd.Parameters.Add("@LogonName", SqlDbType.VarChar).Value = usr;

        SqlDataReader dr = DBCmd.ExecuteReader();
        dr.Read();

        // ContactPerson.Text = dr["FirstName"].ToString() + " " + dr["LastName"].ToString();
        // Notes.Text = dr["Email"].ToString();  // usr.ToString() + "@careersourcebroward.com"; // "Note: Your department is " + dr["Department"].ToString();

        email01.SelectedValue = dr["Email"].ToString();  // usr.ToString() + "@careersourcebroward.com";

        //if (!IsPostBack)
        //{
        //    Department.Text = dr["Department"].ToString();
        //}
        dpt = dr["Department"].ToString();

        dr.Close();
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
    DBCmd.Dispose();
    DBConn.Close();
    DBConn = null;

    // ############################################################################################  START ACCESS  #####################################
    //  Add and edit access list.  deptAccess is department access only.  allAccess is all access.  Add: IValentin |  Use same case as in Active Directory
    string[] deptAccess = {
    "mbateman",
    "rmoffett",
    "CCondon",
    "rpickett",
    "JLloyd",
    "rdaniels",
    "LKing",
    "SBreslin",
    "BCevieux",
    "bcharles",
    "TWeaver",
    "SGonzalez",
    "VSaget",
    "pchernofsky",
    "KRedford",
    "VSpellsAnderson",
    "jconnelly"
};
    string[] allAccess = {
    "MCJ",
    "chylton",
    "ykobrin",
    "CAzor",
    "mklincewicz",
    "mmagill",
    "tash",
    "dmegnin",
    "dhmegnin",
    "GValme",
    "gvalme",
    "mwatson",
    "lelmore",
    "IValentin",
    "TThomas",
    "AWiner",
    "PScott",
    "KKangal",
    "CCarcillo",
    "KHartzog",
    "CJohnson"

    };
    int pos01 = Array.IndexOf(deptAccess, usr);
    int pos02 = Array.IndexOf(allAccess, usr);

    if (pos01 > -1 && dpt == Department.SelectedItem.ToString() || pos02 > -1)  // (AND Department = usr's department)  (OR usr in master list for all access)  (use position numbers in the array and ElseIf like the color codes for accesses?)
    {
        //this.GridView1.AutoGenerateDeleteButton = true;
        this.GridView1.Columns[0].Visible = true;
        Submit.Visible = true;
        Label1.Visible = false;
    }
    else
    {
        //this.GridView1.AutoGenerateDeleteButton = false;  //This adds a new "generated" column and throws off the column index counts.
        this.GridView1.Columns[0].Visible = false;
        Submit.Visible = false;
        Label1.Visible = true;
    }
    // ############################################################################################  END ACCESS  #####################################
    /*
     * 
     * The type or namespace name 'Linq' does not exist in the namespace 'System.Data' (are you miss...
     * May 26, 2008 01:30 PM
     * Hi,
     * I hope that you fixed the problem, just in case you did not add this line into web config where other assembly's are
     * <add assembly="System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
     * */
    Label1.Text = "Note: " + usr.ToString() + ", " + pos01.ToString() + ", " + pos02.ToString() + ", " + dpt;
}

protected void Submit_Click(object sender, EventArgs e)
{
    // Call InsertNewRecord
    InsertNewRecord();
    GridView1.DataBind();
    Active.Visible = true;
}

标签: c#vb.netmethods

解决方案


只需将您的代码移动到具有所需参数的方法或类(最适合的)中。这是您在 C# 中的修改版本:

 // ConnectionString make it globle access inside this class
    private string ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString;

    protected void PopulateReviewerDDL()
    {
        // Currently logged in user:  
        var iUserName = GetCurrentUser();

        try
        {
            var reviewerName = GetReviewerName(iUserName, ConnectionString);

            if(reviewerName != null)
            {
                lblUserName.Text = reviewerName;

                if (!ddlReviewerName.Items.FindByText(reviewerName) == null)
                    ddlReviewerName.Text = reviewerName;
                else
                    Response.Redirect("NoAccess.htm", false);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }

    protected string GetCurrentUser()
    {
        return Right(Request.ServerVariables("AUTH_USER"), (Request.ServerVariables("AUTH_USER").Length - 6));
    }

    protected string GetReviewerName(string username, string connectionString)
    {
        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(connectionString))
            throw new ArgumentNullException("Username or ConnectionString is Empty");

        string fullName = null;

        try
        {
            using (var connection = new SqlConnection(connectionString))
            using (var command = new SqlCommand("SELECTADISNames", connection))
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                connection.Open();
                command.Parameters.Add("@LogonName", SqlDbType.VarChar).Value = username;

                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        fullName = reader["FirstName"].ToString() + " " + LastName = reader["LastName"].ToString();
                    }
                }

            }
        }
        catch (SqlException ex) // we need to catch sql errors only 
        {
            throw new Exception(ex.Message);
        }

        return fullName;
    }

推荐阅读