简体   繁体   English

如何在 ASP.NET 中获取 Windows 用户名?

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

Fairly new to this but I have been trying to create a ASP.NET website to archive files.对此相当陌生,但我一直在尝试创建一个 ASP.NET 网站来存档文件。 I want to capture the Windows username so when the user inserts a file, a record is kept of who inserted it.我想捕获 Windows 用户名,以便当用户插入文件时,会保留插入文件的记录。 I have a table of users that will be using the site, giving the username a reference for records.我有一个将使用该站点的用户表,为用户名提供记录参考。 When I am testing in a development environment everything works correctly and I can see the record created.当我在开发环境中进行测试时,一切正常,我可以看到创建的记录。 However, on the server no record is being created and I get this returned to me:但是,在服务器上没有创建记录,我得到了这个返回给我:

'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###'

I have tried enabling Windows Authentication in IIS and tried using these:我尝试在 IIS 中启用 Windows 身份验证并尝试使用这些:

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

The code I am using to pass the username down to the stored procedure is:我用来将用户名传递给存储过程的代码是:

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

And the stored procedure is just而存储过程只是

SELECT PersonID FROM Person WHERE WindowsName = @userName

Not sure I am looking in the right places but hopefully, this is enough to be pointed in the right direction.不确定我是否在正确的地方寻找,但希望这足以指向正确的方向。

EDIT:编辑:

This is the code I am using to insert the file:这是我用来插入文件的代码:

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 in debugging is correctly returning my name, also userID knows my ID which in this case is 8. On the server it seems to come back with -1.调试中的userName正确返回我的名字, userID也知道我的 ID,在这种情况下是 8。在服务器上,它似乎返回 -1。

Okay so after hours of searching I managed to find a solution that worked for me.好的,经过数小时的搜索,我设法找到了对我有用的解决方案。 In web.config under <system.web> , I already had this code:<system.web>下的web.config ,我已经有了这个代码:

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

The bit I seemed to be missing was:我似乎缺少的一点是:

<identity impersonate ="true"/>

Hopefully this can help anyone that finds themselves in this situation!希望这可以帮助任何发现自己处于这种情况的人!

Link to @gokul answer for more detail here !链接到@gokul 答案以获取更多详细信息

So, the issue seems to be with setting up windows authentication in your server.因此,问题似乎与在您的服务器中设置 Windows 身份验证有关。 Check查看

  1. enabling authentication in IIS在 IIS 中启用身份验证
  2. web.config file for authentication mode = 'windows' line用于身份验证模式的 web.config 文件 = 'windows' 行

and have a look in https://docs.kentico.com/k10/managing-users/user-registration-and-authentication/configuring-windows-ad-authentication for setting up AD authentication.并查看https://docs.kentico.com/k10/managing-users/user-registration-and-authentication/configuring-windows-ad-authentication以设置 AD 身份验证。

Hope this helps you :)希望这对你有帮助:)

There is something in your code that seems odd您的代码中有些东西看起来很奇怪

you said that you are getting the username like this:你说你得到的用户名是这样的:

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

But below you are passing its value directly using Environment.UserName like this:但在下面,您直接使用 Environment.UserName 传递其值,如下所示:

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

Is that really what you meant?你真的是这个意思吗? Besides, I strongly recommend you to LOG the userID that you are getting in the server, it will make your life easier, you can use Nlog for that.此外,我强烈建议您记录您在服务器中获取的用户 ID,这将使您的生活更轻松,您可以使用Nlog

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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