C#面:在 MVC 中如何执行 Windows 认证?

在 MVC 中执行 Windows 认证可以通过以下步骤实现:

  1. 在 Web.config 文件中启用 Windows 身份验证。找到 <system.web> 节点,并确保已经添加或者设置。
  2. 在 Controller 的 Action 方法上使用 Authorize 属性来限制只有经过 Windows 身份验证的用户才能访问该 Action 方法。
  3. 在 View 中可以使用 User.Identity.Name 来获取当前经过 Windows 身份验证的用户名。

示例代码:

在 Web.config 文件中添加以下配置:

html 复制代码
<system.web>
  <authentication mode="Windows" />
  <authorization>
    <deny users="?" />
  </authorization>
</system.web>

在 Controller 中添加以下代码:

cs 复制代码
[Authorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        string username = User.Identity.Name;
        // 其他逻辑
        return View();
    }
}

在 View 中可以使用以下代码显示当前用户的用户名:

cs 复制代码
<p>Welcome, @User.Identity.Name!</p>

注意,执行 Windows 认证需要确保 IIS 服务器已经启用了 Windows 身份验证,并且用户的浏览器也支持 Windows 身份验证。

相关推荐
quantdash_cc4 分钟前
历史数据断层与REST请求慢到崩溃?QuantDash高性能量化数据API终极解决方案
开发语言·python·缓存·php·量化·quantdash
breeze jiang4 分钟前
Next.js 16 App Router 实战:从 About、Blog 动态路由到全局 404
开发语言·javascript·ecmascript
熊野君8 分钟前
Prompt / RAG / 规则 / Skills —— 定位、协作与实现路线
开发语言·python
界面开发小八哥28 分钟前
界面控件DevExpress XAF v26.1新版亮点——AI Agent Skills
ai·c#·跨平台·devexpress·ui开发·xaf
山甫aa41 分钟前
JavaWeb后端开发学习手册
java·开发语言·数据库·学习·mysql·springboot·web
zlinear数据采集卡1 小时前
数据采集卡从入门到精通(42):项目实战三——设备预测性维护系统,从布点到预警
开发语言·单片机·嵌入式硬件·安全·fpga开发
csdn_aspnet1 小时前
C# 高效便利的处理数据
开发语言·windows·c#
淡海水1 小时前
03-02-线性-List-T-动态数组布局-扩容与操作成本
数据结构·windows·c#·list·编译·clr·机器码
Chester_19991 小时前
CSP202209.B何以包邮?
c语言·开发语言
caimouse1 小时前
ReactOS 窗口系统分析(13):滚动条 — scrollbar.c + scrollex.c
c语言·开发语言·reactos