簡體   English   中英

如何在 ASP.NET 中獲取 Windows 用戶名?

[英]How to get Windows username in ASP.NET?

對此相當陌生,但我一直在嘗試創建一個 ASP.NET 網站來存檔文件。 我想捕獲 Windows 用戶名,以便當用戶插入文件時,會保留插入文件的記錄。 我有一個將使用該站點的用戶表,為用戶名提供記錄參考。 當我在開發環境中進行測試時,一切正常,我可以看到創建的記錄。 但是,在服務器上沒有創建記錄,我得到了這個返回給我:

'The INSERT statement conflicted with the FOREIGN KEY constraint 
"FK_Person_BoxArchive_LastUpdate". The conflict occurred in database 
"BoxManagement", table "dbo.Person", column 'PersonID'.###-1###'

我嘗試在 IIS 中啟用 Windows 身份驗證並嘗試使用這些:

string userName = HttpContext.Current.User.Identity.Name.Replace(".", " ");
WindowsIdentity identity = HttpContext.Current.Request.LogonUserIdentity;

我用來將用戶名傳遞給存儲過程的代碼是:

string userName = Environment.UserName.Replace(".", " ");
int userID = -1;
DataTable database = new DataTable();
using (SqlConnection con = new SqlConnection(dbString))
using (SqlCommand cmd = new SqlCommand("GetUserID", con))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@userName", Environment.UserName);
    con.Open();

    using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
    {
        rdr.Read();
        userID = rdr.GetInt32(rdr.GetOrdinal("PersonID"));
        rdr.Close();
    }
}

而存儲過程只是

SELECT PersonID FROM Person WHERE WindowsName = @userName

不確定我是否在正確的地方尋找,但希望這足以指向正確的方向。

編輯:

這是我用來插入文件的代碼:

DataTable database = new DataTable();
string dbString = ConfigurationManager.ConnectionStrings["connArchiveDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(dbString))
using (SqlCommand cmd = new SqlCommand("dbo.InsertAccountFile", con))
{
    try
    {
        int FileType = Int32.Parse(ddlInAccFileType.SelectedValue);
        string policyNumber = "";
        DateTime closedPolicy = new DateTime(1900, 01, 01);

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@boxID", ddlInAccBox.Text);
        cmd.Parameters.AddWithValue("@policyNumber", policyNumber);
        cmd.Parameters.AddWithValue("@fileReference", tbInAccReference.Text);
        cmd.Parameters.AddWithValue("@archivedbyID", userID);
        cmd.Parameters.AddWithValue("@dateArchived", archivedDate);
        cmd.Parameters.AddWithValue("@closedPolicy", closedPolicy);
        cmd.Parameters.AddWithValue("@closedFile", tbInAccClosedDate.Text);
        cmd.Parameters.AddWithValue("@filetypeID", FileType);
        cmd.Parameters.AddWithValue("@comment", tbInAccComment.Text);
        cmd.Parameters.AddWithValue("@expectedDestruction", destructionDate);
        cmd.Parameters.AddWithValue("@lastupdateID", userID);
        cmd.Parameters.AddWithValue("@updatedDate", updateDate);

        SqlParameter archiveParameter = new SqlParameter
        {
            ParameterName = "@boxArchiveID",
            SqlDbType = SqlDbType.Int,
            Direction = ParameterDirection.Output
        };

        SqlParameter messageParameter = new SqlParameter
        {
            ParameterName = "@returnMessage",
            SqlDbType = SqlDbType.VarChar,
            Size = 255,
            Direction = ParameterDirection.Output
        };

        cmd.Parameters.Add(archiveParameter);
        cmd.Parameters.Add(messageParameter);

        con.Open();
        cmd.ExecuteNonQuery();

        string returnMessage = messageParameter.Value.ToString();

        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + returnMessage + "###" + archiveParameter.Value.ToString() + "###" + "')", true);
        }

        catch (Exception ex)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + ex.Message.ToString() + "')", true);
            return;
        }

        finally
        {
            con.Close();                    
        }                
}
ALTER PROCEDURE [dbo].[InsertAccountFile] 
    @boxID INT,
    @policyNumber VARCHAR(255),
    @fileReference VARCHAR(255),
    @archivedbyID INT,
    @dateArchived SMALLDATETIME,
    @closedPolicy SMALLDATETIME,
    @closedFile SMALLDATETIME,
    @filetypeID INT,
    @comment VARCHAR(255),
    @expectedDestruction SMALLDATETIME,
    @lastupdateID INT,
    @updatedDate SMALLDATETIME,     
    @boxArchiveID INT OUTPUT,
    @returnMessage VARCHAR(255) OUTPUT
AS
BEGIN
    SET NOCOUNT ON

    IF NOT EXISTS(SELECT * FROM BoxArchive WHERE BoxID = @boxID AND FileReference = @fileReference)

    BEGIN
        BEGIN TRY
            INSERT INTO BoxArchive (PolicyNumber, FileReference, ArchivedByID, DateArchived, DatePolicyClosed, ClosedFileDate, BoxID, FileTypeID, Comment, ExpectedDestructionDate, 
                                LastUpdateID, LastUpdateDate) 
            VALUES (@policyNumber, @fileReference, @archivedbyID, @dateArchived, @closedPolicy, @closedFile, @boxID, @filetypeID, @comment, @expectedDestruction,
                                @lastupdateID, @updatedDate)

            SET @returnMessage = 'Success.'
            SET @boxArchiveID = IDENT_CURRENT('BoxArchive') 
        END TRY

        BEGIN CATCH
            SET @returnMessage = ERROR_MESSAGE()
            SET @boxArchiveID = -1
        END CATCH
    END

    ELSE

    BEGIN
        SET @returnMessage = 'Error: "' + @fileReference + '" already exists in this box.' 
        SET @boxArchiveID = -1
    END

調試中的userName正確返回我的名字, userID也知道我的 ID,在這種情況下是 8。在服務器上,它似乎返回 -1。

好的,經過數小時的搜索,我設法找到了對我有用的解決方案。 <system.web>下的web.config ,我已經有了這個代碼:

<authentication mode="Windows" />
<authorization>
  <allow users="*" />
</authorization>

我似乎缺少的一點是:

<identity impersonate ="true"/>

希望這可以幫助任何發現自己處於這種情況的人!

鏈接到@gokul 答案以獲取更多詳細信息

因此,問題似乎與在您的服務器中設置 Windows 身份驗證有關。 查看

  1. 在 IIS 中啟用身份驗證
  2. 用於身份驗證模式的 web.config 文件 = 'windows' 行

並查看https://docs.kentico.com/k10/managing-users/user-registration-and-authentication/configuring-windows-ad-authentication以設置 AD 身份驗證。

希望這對你有幫助:)

您的代碼中有些東西看起來很奇怪

你說你得到的用戶名是這樣的:

string userName = Environment.UserName.Replace(".", " ");

但在下面,您直接使用 Environment.UserName 傳遞其值,如下所示:

cmd.Parameters.AddWithValue("@userName", Environment.UserName);

你真的是這個意思嗎? 此外,我強烈建議您記錄您在服務器中獲取的用戶 ID,這將使您的生活更輕松,您可以使用Nlog

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM