在ASP.NET MVC 3中,Windows身份验证可能无效的原因有很多。以下是一些常见的解决方法和代码示例:
确保IIS设置正确。在IIS管理器中,选择你的应用程序池,然后右键单击“高级设置”,将“启用32位应用程序”设置为“True”。
确保你的应用程序的身份验证授权设置为启用Windows身份验证。在Global.asax文件中的Application_Start方法中添加以下代码:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
// 启用Windows身份验证
GlobalFilters.Filters.Add(new AuthorizeAttribute());
}
确保你的控制器或操作方法上没有使用[AllowAnonymous]特性,否则它将覆盖Windows身份验证。
确保你的操作方法或视图没有包含[Authorize]特性,因为它将要求用户进行身份验证。
确保你的浏览器可以自动进行Windows身份验证。在Internet选项中的安全选项卡下,将局域网区域的安全级别设置为“自定义级别”,然后将“启用集成Windows验证”设置为“自动”。
如果你仍然遇到问题,可以尝试在Global.asax文件中的Application_AuthenticateRequest方法中手动进行身份验证:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
// 手动进行Windows身份验证
if (Request.IsAuthenticated || !Request.LogonUserIdentity.IsAuthenticated)
{
return;
}
string username = Request.LogonUserIdentity.Name;
string[] roles = new string[] { "Role1", "Role2" };
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(username), roles);
}
请注意,这将创建一个通用的主体并将其分配给当前的HTTP上下文。你需要根据你的具体需求进行适当的调整。
希望这些解决方法能够帮助你解决ASP.NET MVC 3中的Windows身份验证无效的问题。