重定向(URL)无法正常工作 [英] Redirect(url) not working

查看:193
本文介绍了重定向(URL)无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.net MVC3的背景下,我有一个控制器动作,它试图重定向到一个特定的URL此行code的。

In context of ASP.net MVC3, I have this line of code in a controller action, which tries to redirect to a particular url.

return Redirect(returnUrl);

RETURNURL是包含/首页/索引/的字符串。出于某种原因,重定向不会发生,我仍然在同一屏幕上。我试着删除了结尾的斜线,但没有成功。任何想法,为什么重定向不会发生?

returnUrl is a string that contains "/Home/Index/". For Some reason the redirect is not taking place and I remain on the same screen. I tried removing the trailing slash but no success. Any ideas why the Redirect does not take place?

推荐答案

重定向法的目的是用来重定向到您的网站的外部URL,并通过将其绝对URL。如果您需要重定向到属于你的网站会得到更好的使用该另一个控制器动作:

The Redirect method is intended to be used to redirect to external urls of your site and by passing it an absolute url. If you need to redirect to another controller action that belongs to your site it would be better to use this:

return RedirectToAction("Index", "Home");

这样,你不再是硬编码网址和code是路由变化不那么脆弱。

This way you are no longer hardcoding urls and your code is less fragile to route changes.

这是说,如果你调用控制器动作执行此与AJAX重定向你不能指望它来随时随地浏览器重定向=>这显然会留在同一页上。 AJAX请求将成功以下所有重定向和成功的回调,您将获得好像是要求没有AJAX /首页/指数网​​址的最终HTML

This being said, if you are invoking the controller action that performs this redirect with AJAX you cannot expect it to redirect the browser anywhere => it will obviously stay on the same page. The AJAX request will succeed following all redirects and in the success callback you will get the final HTML of the /Home/Index url as if it was requested without AJAX.

如果你想在一个AJAX的成功回调重定向叫你可以有例如您的控制器动作返回一个JSON对象,指示要重定向到目标网址:

If you want to redirect in the success callback of an AJAX call you could have your controller action return for example a JSON object indicating the target url you want to redirect to:

return Json(new { redirectToUrl = Url.Action("Index", "Home") });

和在回调中使用 window.location.href 功能:

success: function(result) {
    window.location.href = result.redirectToUrl;
}

这篇关于重定向(URL)无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆