gpt4 book ai didi

asp.net-mvc - ASP.NET MVC : Response. Redirect(url, TRUE) 不会停止请求处理

转载 作者:行者123 更新时间:2023-12-01 17:53:28 26 4
gpt4 key购买 nike

我有一个用两个自定义 ActionFilterAttribute 装饰的方法。

[RequiresAuthentication(Order = 1)]
[ToonAction(Order = 2)]
public ActionResult Browse(...

RequiresAuthentication 属性来自 this article

在 RequiresAuthentication 中,在 OnActionExecuting 上我这样做:

 filterContext.HttpContext.Response.Redirect(loginUrl, true);

该行is被执行,并且参数都符合预期。问题是,执行上面的行后,我执行了下一个属性(ActionFilterAttribute),就好像重定向不起作用一样,它只是继续执行请求,而不是简单地重定向浏览器。

问题:我还需要做什么来创建请求处理程序

这是一个完整的方法:

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
//redirect if not authenticated
var identity = filterContext.HttpContext.User.Identity;
if (!identity.IsAuthenticated) {
//use the current url for the redirect
string redirectOnSuccess = filterContext.HttpContext.Request.Url.PathAndQuery;

//send them off to the login page
string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
filterContext.HttpContext.Response.Redirect(loginUrl, true);
// filterContext.Result = new HttpUnauthorizedResult();
// filterContext.HttpContext.Response.StatusCode = 0x191;
}
}

最佳答案

您希望将 filterContext 上的结果设置为 RedirectResult,而不是对响应进行重定向。

 filterContext.Result = new RedirectResult { Url = loginUrl };

编辑:正如@Hunter Daley建议的那样,更好的机制是使用AuthorizeAttribute(如果它适合您)。如果您确实有 AuthorizeAttribute 不起作用的身份验证/授权方案,那么从它派生您的自定义属性可能会比更通用的 ActionFilterAttribute 更好。无论如何,正确的技术是设置结果而不是直接与响应交互。您可能想查看实际的 AuthorizeAttribute 源 http://www.codeplex.com/aspnet寻求想法。

我有 custom authorization 的样本我的博客上的代码,http://farm-fresh-code.blogspot.com ,也是。

关于asp.net-mvc - ASP.NET MVC : Response. Redirect(url, TRUE) 不会停止请求处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2187323/

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