首页 > 解决方案 > 使用控制器上下文之外的查询参数重定向到控制器

问题描述

我在网上看了很多次,但一直没能找到解决我目前困境的办法。正如标题所示,我正在尝试使用以下代码将用户重定向到我的视图控制器之一:

// this is in a service that's beyond the Controller scope
httpContext.Response.Redirect("/Login");

这很好用;但是,我还需要传入一个查询参数。本质上,我希望做这样的事情:

// this is in a service that's beyond the Controller scope
httpContext.Response.Redirect("/Login?NoAccess=true");

我的视图控制器如下所示:

[AllowAnonymous]
[HttpGet("~/Login")]
public async Task<IActionResult> Index([FromQuery]bool noAccess = false)
{
     // implementation
}

正如人们可能想象的那样,这不起作用,并且该值没有传递给我的控制器。

是否可以使用控制器上下文之外的重定向来传递查询参数?

谢谢,鲁本

标签: asp.net-mvcasp.net-corehttpcontextresponse.redirect

解决方案


尝试使用RedirectToActionorRedirectToRoute代替。将返回一个 IActionResult 来进行重定向。使用它,您可以指定带有参数的对象。像这样:

public IActionResult Action()
{
    return this.RedirectToAction("Index", "ControllerName", new {
        noAccess = true
    });
}

推荐阅读