2

我首先使用 mvc 3 代码。将数据从 SecurityAttribute 类传递给 Controller 时遇到问题。我实际上想在登录页面上重定向用户并显示消息。为此,我覆盖了 SecurityAttribute 类中的 AuthorizeCore 方法。在这种方法中,我无法直接使用 session、cookie、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; 
        }
4

1 回答 1

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)
{
    ...
}
于 2012-06-14T11:47:19.300 回答