gpt4 book ai didi

asp.net - 无法将数据从 SecurityAttribute 类传递到 MVC3 中的 Controller

转载 作者:行者123 更新时间:2023-12-04 18:19:13 25 4
gpt4 key购买 nike

我首先使用 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;
}

最佳答案

首先,您不应该在 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 action 将错误信息作为 action 参数:
public ActionResult LogOn(string errorMessage)
{
...
}

关于asp.net - 无法将数据从 SecurityAttribute 类传递到 MVC3 中的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11032319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com