一种可能性是使用会话变量。另一个是将此信息保存在存储在cookie中的身份验证票证的userData
部分中。然后,您可以编写一个自定义主体和授权属性,它将读取身份验证Cookie,解密凭单并检索信息。
UPDATE:
正如在评论部分要求这里的第二种方法可以如何实现的例子。
我们先定义一个自定义主体:
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的一部分:
[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");
}
}
而最后一部分是使用自定义的授权属性上的一些动作:
[CustomAuthorize]
public ActionResult Foo()
{
var businessId = ((CustomPrincipal)User).BusinessId;
...
}
你可以写一个基本控制器和揭露这个定义主体的属性,以避免铸造你需要访问业务ID每次。
感谢达林,什么被认为是最佳实践? – 2011-04-30 09:24:21
@Diver Dan,我个人会尽量避免使用会话,因为我会尽量避免会话。 – 2011-04-30 09:25:03
谢谢我会对创建自定义主体属性做一些研究 – 2011-04-30 09:32:36