根据当前用户ID从成员资格表中返回一个值

时间:2011-04-30 08:07:13

标签: asp.net asp.net-mvc-3

我使用的是使用asp.net会员数据库的mvc3。我创建了一个名为Business的表,其中包含UserId(来自aspnet_users表),BusinessId和BusinessName字段。

我知道使用Context.CurrentUser .....我可以获得用户名等。

我需要能够将BusinessId存储在我的任何控制器都可以访问的地方,这是最好的方法吗?我不希望每次都回调数据库以获得基于当前用户的BusinessId

我是否在某处创建了context.session?

任何指针都会非常有用!

1 个答案:

答案 0 :(得分:0)

一种可能性是使用会话变量。另一个是将此信息保存在存储在cookie中的身份验证票证的userData部分中。然后,您可以编写自定义主体和授权属性,该属性将读取身份验证cookie,解密故障单并检索信息。


更新:

根据评论部分的要求,这里有一个如何实施第二种方法的例子。

我们从定义自定义主体开始:

public class CustomPrincipal : GenericPrincipal
{
    public CustomPrincipal(IIdentity identity, string[] roles, string businessId)
        : base(identity, roles)
    {
        BusinessId = businessId;
    }
    public string BusinessId { get; private set; }
}

然后是自定义授权属性:

public class CustomAuthorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (isAuthorized)
        {
            var cookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            var ticket = FormsAuthentication.Decrypt(cookie.Value);
            var identity = new GenericIdentity(ticket.Name);
            var principal = new CustomPrincipal(identity, null, ticket.UserData);
            httpContext.User = principal;
        }

        return isAuthorized;
    }
}

接下来我们需要修改登录操作,以便业务ID包含在身份验证cookie的userData部分中:

[HttpPost]
public ActionResult LogOn(string username, string password)
{
    SomeUserModel user = FetchUserFromSomewhere(username, password);
    if (user == null)
    {
        // wrong username/password => redisplay login form
        return View();
    }

    var ticket = new FormsAuthenticationTicket(
        1,
        username,
        DateTime.Now,
        DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
        false,
        user.BusinessId // that's where we store the business id
    );
    var encryptedTicket = FormsAuthentication.Encrypt(ticket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
    {
        HttpOnly = true,
        Secure = FormsAuthentication.RequireSSL
    };
    Response.AppendCookie(cookie);
    return RedirectToAction("Index", "SomeController");
}
}

最后一部分是对某些操作使用自定义authorize属性:

[CustomAuthorize]
public ActionResult Foo()
{
    var businessId = ((CustomPrincipal)User).BusinessId;
    ...
}

您可以编写一个基本控制器并将此自定义主体公开为属性,以避免每次需要访问业务ID时进行转换。