asp.net-mvc – MVC – 重定向在构造函数内

我想知道如果我需要这样做,我可以如何重定向控制器构造函数中的请求?

例如:
在构造函数内,我需要初始化具有动态值的对象,在某些情况下,我不想这样做,在这种情况下,我想重定向到其他地方。
以相同的方式,构造函数的其余部分既不会执行“原始跟随操作”。

我该怎么做?
谢谢

编辑#1

最初我用:

public override void OnActionExecuting(ActionExecutingContext filterContext)

在那里我可以重定向到一些其他控制器/动作/ url,但稍后的时间,我需要更改我的控制器,我在其中构造函数中初始化一个变量,并有一些代码真的需要重定向请求:P

我也需要这一点,因为OnActionExecuting在控制器构造函数后执行
在我的逻辑中,重定向需要在那里完成。

解决方法

执行控制器构造函数内的重定向不是一个好的做法,因为上下文可能没有被初始化。标准做法是编写自定义操作属性并覆盖 OnActionExecuting方法并在其中执行重定向。例:
public class RedirectingActionAttribute : ActionFilterattribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        if (someConditionIsMet)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "someOther",action = "someAction"
            }));
        }
    }
}

然后使用此属性装饰要重定向的控制器。要非常小心,不要装饰你正在重定向到这个属性的控制器,否则你将会遇到一个无休止的循环。

所以你可以:

[RedirectingAction]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        // This action is never going to execute if the 
        // redirecting condition is met
        return View();
    }
}

public class SomeOtherController : Controller
{
    public ActionResult SomeAction()
    {
        return View();
    }
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....