我在Visual Studio中使用MVC4的默认Web应用程序模板。成功登录后如何编写授权属性以重定向用户?此属性应如下所示:[UserRedirect(" username")]是否有人使用" username"应该进行登录重定向。我在哪里应用此属性?到登录页面或索引?谢谢你的回答。
答案 0 :(得分:0)
您需要覆盖AuthorizeAtribute的OnAuthorization方法
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class UserRedirectAttribute: AuthorizeAttribute
{
public string UserName{ get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.onAuthorization(filterContext);
if(base.AuthorizeCore(filterContext.HttpContext) == true)
{
//here put all the a logic for redirect condition ()
if(filterContext.HttpContext.User.Identity.Name.Equals(this.UserName,StringComparer.Ordinal)
{
//if you should do the redirect
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Redirect controller name",
action = "Redirect action name"
})
);
}
}
}
}
关于用法:
如果是要替换默认授权属性的authorize属性,则应该在任何授权的操作/控制器上
修改强>:
根据您的上一条评论,您根本不必使用属性。只需在登录操作结束时添加重定向逻辑:
[HttpPost]
public ActionResult Login(LoginModel model)
{
bool userAuthenticationResult = // here goes your authentication logic
if(userAuthenticationResult && HttpContext.User.Identity.Name.Equals(this.UserName,StringComparer.Ordinal))
{
//setup cookie/token any other things you need for the authentication to work
return RedirectToAction("ActionName","ControllerName");
}
}