你如何找到在C#中的用户名/身份

编程入门 行业动态 更新时间:2024-10-28 16:20:11
本文介绍了你如何找到在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,WCF等)的工作 - 但它依赖于身份被预先设置(因为它是应用程序定义)。例如,在一个WinForm你可能会使用当前用户的Windows身份:

This allows the same code to work in many different models (winform, asp, 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#中的用户名/身份

本文发布于:2023-11-09 17:12:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572952.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:用户名   身份

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!