作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的 ASP.NET MVC 应用程序中,我试图创建一个自定义的 HttpContent.User 对象。我首先创建了一个实现 IPrincioal 的 Member 类。
public class Member : IPrincipal
{
public string Id { get; set; }
public IIdentity Identity { get; set; }
public bool IsInRole(string role) { throw new NotImplementedException(); }
...
}
FormsAuthentication.SetAuthCookie(email, false);
HttpContext.User = member;
if (User.Identity.IsAuthenticated) { ... }
public IIdentity Identity
做什么成员实例上的属性。 这样我就可以像这样使用 HttpContext.User 对象:
IsAuthenticated = HttpContext.User.Identity.IsAuthenticated;
ViewBag.IsAuthenticated = IsAuthenticated;
if (IsAuthenticated) {
CurrentMember = (Member)HttpContext.User;
ViewBag.CurrentMember = CurrentMember;
}
最佳答案
Principal 不是您可以在编写 auth cookie 时设置一次然后忘记的东西。在后续请求期间,将读取 auth cookie 并且 IPrincipal
/IIdentity
在执行操作方法之前重建。发生这种情况时,尝试转换 HttpContext.User
到您的定制 Member
type 会抛出异常。
一种选择是拦截 ActionFilter
,然后包装标准实现。
public class UsesCustomPrincipalAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var systemPrincipal = filterContext.HttpContext.User;
var customPrincipal = new Member(systemPrincipal)
{
Id = "not sure where this comes from",
};
filterContext.HttpContext.User = customPrincipal;
}
}
public class Member : IPrincipal
{
private readonly IPrincipal _systemPrincipal;
public Member(IPrincipal principal)
{
if (principal == null) throw new ArgumentNullException("principal");
_systemPrincipal = principal;
}
public string Id { get; set; }
public IIdentity Identity { get { return _systemPrincipal.Identity; } }
public bool IsInRole(string role)
{
return _systemPrincipal.IsInRole(role);
}
}
IPrincipal
开箱即用的内容。和
IIdentity
实现。您仍然可以调用
IsAuthenticated
在
IIdentity
,甚至
IsInRole(string)
在
IPrincipal
.您唯一获得的是额外的
Id
您的自定义属性
IPrincipal
实现(尽管我不确定它来自哪里或为什么需要它)。
关于asp.net-mvc - 如何在 ASP.NET MVC 中为自定义用户对象实现标识?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11912125/
我是一名优秀的程序员,十分优秀!