【发布时间】:2015-10-19 17:21:40
【问题描述】:
我已经阅读了很多关于这个主题的问题和答案,但没有一个能帮助我解决这个问题。
我遇到的问题是 HttpContext.Current.User 或只是 User 属性的类型是 RolePrincipal 而不是我的自定义主体。
这是一个使用 Windows 身份验证的 MVC 5 Web 应用程序(仅限 Intranet 应用程序)。我的自定义主体是WindowsPrincipal 的子类,我确实实现了自己的RoleProvider 以用于授权属性标签。
当我尝试通过在当前 HttpContext 上将其从 IPrincipal 强制转换为我的自定义主体来使用该主体时,我收到一条错误消息,指出它是 RolePrincipal 类型,显然无法将其强制转换为我的自定义主体。我在Application_PostAuthenticationRequest 事件中设置我的自定义主体:
protected void Application_PostAuthenticationRequest(object sender, EventArgs e)
{
if (User == null)
return;
using(EntityContext db = new EntityContext ())
{
var user = db.Users.SingleOrDefault(u => u.ADName.Equals(User.Identity.Name));
HttpContext.Current.User = new PcsPrincipal((WindowsIdentity)User.Identity, user);
}
}
当我在该方法中放置断点时,它似乎永远不会被调用,这可以解释为什么它没有设置为我的自定义主体。
我已经查看了以下 QA,但他们未能解决问题:
-
using custom IPrincipal and IIdentity in MVC3 - 在 Global.asax.cs 的 Init 方法中添加了事件处理程序的注册。似乎没有什么不同。此外,
_application变量在 MVC5 中似乎无效。 - RoleProvider dosn't work with custom IIdentity and IPrincipal on server - 在 web.config 文件中进行了更改,但这会在运行时导致各种错误,错误提示 ASP.NET 管道配置不正确。
我做错了什么没有设置主体?如果需要发布更多代码,请告诉我。
编辑:在 WindowsAuthentication.OnAuthenticate 事件中将 HttpContext.Current.User 设置为我的自定义主体不能解决此问题。使用该方法表现出完全相同的行为。
【问题讨论】:
标签: c# asp.net asp.net-mvc-5 asp.net-identity windows-authentication