简体   繁体   English

从 ASP.NET MVC 中的 class 方法重定向到 Controller

[英]Redirect to a Controller from class method in ASP.NET MVC

please I have a void method in a class and i want from this method to redirect to an action in a controller, i try to use RedirectToAction but I didn't saw it in the Intellisense, please do you have any idea about how can I redirect from this void method into a Controller Action.请我在 class 中有一个 void 方法,我想从这个方法重定向到 controller 中的一个动作,我尝试使用RedirectToAction但我没有在 Intellisense 中看到它,请问你知道我该怎么做从此 void 方法重定向到 Controller 操作。

I work on ASP.NET MVC Application我在 ASP.NET MVC 应用程序上工作

massive thanks.非常感谢。

You can't.你不能。

You could, using HttpContext.Current.Response.Redirect or something like that, but don't , because then you bypass the entire MVC pipeline.您可以使用HttpContext.Current.Response.Redirect或类似的东西,但不要这样做,因为这样您就绕过了整个 MVC 管道。

A non-controller class doesn't (or at least shouldn't) know that it's being used in an ASP.NET MVC context.非控制器 class 不(或至少不应该)知道它正在 ASP.NET MVC 上下文中使用。 You call a method on a class to let that method perform a particular task.您调用 class 上的方法以让该方法执行特定任务。

If a certain result of that task, again, in an MVC context, should result in your web application redirecting the user to another action, then do so in your controller.如果该任务的某个结果再次在 MVC 上下文中导致您的 web 应用程序将用户重定向到另一个操作,那么在您的 controller 中执行此操作。

So, something like this:所以,像这样:

public ActionResult Foo()
{
    var result = someOtherClass.Bar();

    if (result.WhatEver)
    {
        return RedirectToAction(...);
    }

    return View(...);
}

And yes, this means that Bar() probably shouldn't be void , but return something meaningful.是的,这意味着Bar()可能不应该是void ,而是返回一些有意义的东西。

An you generally also don't want classes you call from controllers return an ActionResult -derived result.您通常也不希望从控制器调用的类返回ActionResult派生的结果。

Use this snippet in your void:在你的空白中使用这个片段:

RedirectToAction("SomeAction").ExecuteResult(this.ControllerContext);

So, use IActionResult to performance the redirect因此,使用 IActionResult 执行重定向

public IActionResult SomeAction()
{
    RedirectToAction("SomePlace", "SomeController");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM