首先,您不应该在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)
{
...
}