你如何找到在C#中的用户名/身份 [英] How do you find the users name/Identity in C#

查看:160
本文介绍了你如何找到在C#中的用户名/身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式找到用户名称使用C#。具体而言,我想获得附加到当前进程的系统/网络用户。我在写一个使用Windows集成安全性的Web应用程序。

I need to programatically find the users name using C#. Specifically, I want to get the system/network user attached to the current process. I'm writing a web application that uses windows integrated security.

推荐答案

身份的抽象看法往往是的IPrincipal / 的IIdentity

The abstracted view of identity is often the IPrincipal/IIdentity:

IPrincipal principal = Thread.CurrentPrincipal;
IIdentity identity = principal == null ? null : principal.Identity;
string name = identity == null ? "" : identity.Name;

这允许同一code在许多不同的模式(的winform,asp.net,WCF等)的工作 - 但它依赖于身份被预先设置(因为它是应用程序定义)。例如,在一个WinForm你可能会使用当前用户的Windows身份:

This allows the same code to work in many different models (winform, asp.net, wcf, etc) - but it relies on the identity being set in advance (since it is application-defined). For example, in a winform you might use the current user's windows identity:

Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

不过,校长也可以完全定制 - 它并不一定涉及到Windows帐户等。另一个应用程序可能会使用一个登录界面,允许任意用户登录:

However, the principal can also be completely bespoke - it doesn't necessarily relate to windows accounts etc. Another app might use a login screen to allow arbitrary users to log on:

string userName = "Fred"; // todo
string[] roles = { "User", "Admin" }; // todo
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userName), roles);

这篇关于你如何找到在C#中的用户名/身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆