0

User.Identity.Nameコントローラー外のクラスで作業するにはどうすればよいですか? クラス内でこのように使用しました

private readonly static string sLogon =  HttpContext.Current.User.Identity.Name.Substring(HttpContext.Current.User.Identity.Name.LastIndexOf(@"\") + 1);

IIS 7.5 運用サーバーで null 参照を再実行します。開発サーバーで動作します。

ここでは、いくつかの代替手段を使用しました。

  • 最初に使用しEnvironment.Usernameました。これは開発でうまく機能します。しかし、出版後ではありません。その後Environment.Username、アプリが実行されるアプリケーション プールの名前が生成されるためです
  • Controller.User.Identity.Nameコントローラーで目的のユーザー名を取得するために使用され、公開前および公開後にうまく機能します。ただし、Class .cs のコンテキストでは使用できません。
  • System.Web.HttpContext.Current.User.Identity.Namenull 参照を生成します。
  • System.Security.Principal.WindowsIdentity.GetCurrent().Nameと同じように動作しますEnvironment.Username

使い方のアイデアはありますか?ありがとう

アップデート

環境によっては、ログイン ID を取得すると、Employee テーブルから EmployeeID や Email などの従業員情報を取得できます。例: Employee テーブルから Employee ID を取得してこのようにアクセスするための 1 つのクラス (コントローラの外部) があります。

string EmployeeID = new EmployeeService().EmployeeID();

private readonly static string sLogon =  HttpContext.Current.User.Identity.Name.Substring(HttpContext.Current.User.Identity.Name.LastIndexOf(@"\") + 1);

public string EmployeeID()
        {
            var employee = new Common().Employee();

            string sID = (from e in employee
                          where (e.LogonID ?? "N/A").ToLower().Contains(sLogon.ToLower())
                          select e.EmployeeID).FirstOrDefault();

            return sID;
        }
4

1 に答える 1

0

反映されたコードによると、Windows 認証の OnAuthenticate イベント中に HttpContext.Current.User が設定されます。

// System.Web.Security.WindowsAuthenticationModule
private void OnAuthenticate(WindowsAuthenticationEventArgs e)
{
    if (this._eventHandler != null)
    {
        this._eventHandler(this, e);
    }
    if (e.Context.User == null)
    {
        if (e.User != null)
        {
            e.Context.User = e.User;
            return;
        }
        if (e.Identity == WindowsAuthenticationModule.AnonymousIdentity)
        {
            e.Context.SetPrincipalNoDemand(WindowsAuthenticationModule.AnonymousPrincipal, false);
            return;
        }
        e.Context.SetPrincipalNoDemand(new WindowsPrincipal(e.Identity), false);
    }
}

運用サーバーで Windows 認証が有効になっていて、匿名認証が無効になっているかどうかを確認する必要がある場合があります。

http://technet.microsoft.com/en-us/library/cc754628(v=WS.10).aspx

于 2013-07-10T05:33:11.970 に答える