MVC3自定义AuthorizeAttribute:如何从控制器中的对象传递 [英] MVC3 Custom AuthorizeAttribute : how to pass in an object from controller

查看:827
本文介绍了MVC3自定义AuthorizeAttribute:如何从控制器中的对象传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含所有登录数据的对象,那是在我的控制器(它切换到MVC3之前编程)。

I have an object that contains all login data, that's in my controller (it was programmed before switching to MVC3).

我想授权添加到网站,所以到目前为止,我有:

I'm trying to add authorization to the site, so so far I have:

public LoginObject MyLoginObject
{
   get;
   set;
}

[CustomAuthorization()]
public ActionResult Index()
{
 return View();
}

public class CustomAuthorization : AuthorizeAttribute
{
   protected override bool AuthorizeCore(HttpContextBase httpContext)
   {
    return true;
    //should be return myLoginObject.IsLoggedIn;
   }
}

反正是有MyLoginObject传递到AuthorizeAttribute类?如果不是我能至少在布尔传球,指定用户是否授权或对象不?

Is there anyway to pass MyLoginObject into the AuthorizeAttribute class? If not could I at least pass in a boolean from the object that specifies if the user is authorized or not?

编辑:我的解决方案基于Zonnenberg的建议

My solution based on Zonnenberg's advice.

public class LoginObject : IPrincipal // Now extends IPrincipal 
{
   ... //old code
   private class IdentityImpl : IIdentity
{
  public string AuthenticationType
  {
    get;
    set;
  }

  public bool IsAuthenticated
  {
    get;
    set;
  }

  public string Name
  {
    get;
    set;
  }
}

public IIdentity Identity
{
  get { return new IdentityImpl { AuthenticationType = "Custom Authentication", IsAuthenticated = this.IsLoggedIn, Name = this.Id}; }
}
}

然后我搬到loginobject的实例为CustomAuthorization

Then I moved the instantiation of loginobject into CustomAuthorization

public override void OnAuthorization(AuthorizationContext filterContext)
{
  // ... Set up LoginObject
    filterContext.RequestContext.HttpContext.User = myLoginObject;

  base.OnAuthorization(filterContext);
}

所以,现在登录,被授权内部完成,我可以调用用户从控制器访问登录。

So now logging in, is done inside the authorization, and I can call User to access the login from the controller.

推荐答案

您可以检查使用wheter的用户登录的 httpContext.User.Identity.IsAuthenticated

You can check wheter the user is logged in by using httpContext.User.Identity.IsAuthenticated.

要存储更多的信息,你可以使用的 HttpContext.User中的对象。你可以写自己的实现的的IPrincipal 的的的的IIdentity 的存储各种登录信息。

To store more information you could use the httpContext.User object. You can write your own implementation of IPrincipal and IIdentity to store all kinds of login information.

另外一种选择是在会话中存储的登录信息。

Other option is to store login info in the Session.

这篇关于MVC3自定义AuthorizeAttribute:如何从控制器中的对象传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆