我首先使用的是mvc 3代码。从SecurityAttribute类传递数据到Controller时面临问题。我实际上想要在登录页面上重定向用户并显示消息。为此,我重写SecurityAttribute类中的AuthorizeCore方法。在这种方法中,我无法直接使用session,cookies,tempdate和viewbag等任何其他解决方案来解决这个问题。谢谢
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.Session["UserID"] == null)
{
//here i am unable to pass message to User/LogOn action.
httpContext.Response.Redirect("~/User/LogOn");
// httpContext.Session["lblMsg"] = "You are not authroize to perform this action.Please Login through different account";
return false;
}
答案 0 :(得分:4)
首先,您不应该在AuthorizeCore
方法内重定向。您应该使用专门用于此目的的HandleUnauthorizedRequest
方法。至于将错误消息传递给LogOn操作,您可以使用TempData:
public class SecurityAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// perform the custom authorization logic here and return true or false
// DO NOT redirect here
return httpContext.Session["UserID"] != null;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Controller.TempData["ErrorMessage"] = "You are not authroize to perform this action.Please Login through different account";
// calling the base method will actually throw a 401 error that the
// forms authentication module will intercept and automatically redirect
// you to the LogOn page that was defined in web.config
base.HandleUnauthorizedRequest(filterContext);
}
}
然后在LogOn操作中:
public ActionResult LogOn()
{
string errorMessage = TempData["ErrorMessage"] as string;
...
}
或者如果您想在LogOn.cshtml
视图中访问它:
<div>@TempData["ErrorMessage"]</div>
另一种可能性是将消息作为查询字符串参数传递,而不是使用TempData:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var values = new RouteValueDictionary(new
{
controller = "User",
action = "LogOn",
errormessage = "You are not authroize to perform this action.Please Login through different account"
});
filterContext.Result = new RedirectToRouteResult(values);
}
然后您可以让LogOn
操作将错误消息作为操作参数:
public ActionResult LogOn(string errorMessage)
{
...
}