重定向到控制器,使用控制器上下文之外的查询参数



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

// 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
}

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

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

谢谢 鲁本

public override async  Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var url = context.Request.Headers["Referer"];//Url for go back
var errorMessage = "An error occured."; //Error Message
var errorCode = 500; 
var redirectUrl = string.Format("/hata?url={0}&errorMessage={1}&errorCodes={2}", url, errorMessage, errorCode);
context.Response.Redirect(redirectUrl);
}

您可以使用字符串。用于发送查询参数的 Format((。

尝试改用RedirectToActionRedirectToRoute。将返回 IActionResult 来执行重定向。有了它,您可以指定带有参数的对象。喜欢这个:

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

你可以试试

public IActionResult Action()
{
return Redirect(Url.Action("Index", "ControllerName") + "?noAccess=true"));
}

另外,您可以尝试添加整个网址,例如:

public ActionResult YourAction()
{
// ...entire url
return Redirect("http://www.example.com");
}

甚至你可以用新的网址返回一个JsonResult,并使用javascript执行重定向。

public ActionResult YourAction()
{
// ...
return Json(new {url = "http://www.example.com"});
}
$.post("@Url.Action("YourAction")", function(data) {
window.location = data.url;
});

最新更新