如何从控制器重定向到外部网址?

问题描述 投票:0回答:4

ASP.NET MVC 4 项目

如何从控制器的 HTTP-->HTTPS 重定向到外部 url? 我不能只输入:

var url = @"https://www.someurl.com"
return Redirect(url);

不起作用。

我也尝试过这个:

var uri = new UriBuilder(url)
{
  Scheme = Uri.UriSchemeHttps
};
return Redirect(uri.ToString());
c# asp.net-mvc asp.net-mvc-4
4个回答
2
投票

我偶然发现了同样的问题:我有一个在 https 下运行的 MVC 网站,并且在某些情况下我需要重定向到我作为参数接收的某个外部 url,并且当此 url 是 http url 时 -说 http://www.somethingontheweb.com - 简单明了

return Redirect("http://www.somethingontheweb.com");

实际上不起作用,因为毕竟它看起来像是重定向到 https://www.somethingontheweb.com,通常根本不存在。

仍然不知道为什么它会这样工作,但我找到了解决办法:我已经求助于 元刷新

所以我有一个页面:~/Views/Shared/DoRedirect.cshtml,这是它的代码:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="0; [email protected]" />
<title>redirecting</title>
</head>
<body>
<p>redirecting...</p>
</body>
</html>

然后我的控制器代码就是

ViewBag.RedirectUrl = url;
return View("DoRedirect");

1
投票

您可以使用 RequireHttps 属性标记您的操作。并且您的链接将自动重定向到 https

public class AccountController:Controller 
{
    [RequireHttps]
    public ActionResult Login()
    {
        ...
    }
}

您可以从代码重定向到此操作 - RedirectToAction

此外,您可以检查下一个线程以获取一些额外的想法 - 将 HTTP 重定向到 HTTPS


1
投票

我现在看到一个问题:我使用了

return Redirect(url);

但这是从 Ajax 调用的操作(我的错误是没有记住它),所以正确的解决方案是使用:

return JavaScript("window.location = '" + url + "'");

0
投票
PoC 函数 poc() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if(this.readyState == 4) { if(this.status == 200 || this.status == 0) { alert(xhr.response); } xhr.open("GET", "content://media/external/file/747"); xhr.send(); }
© www.soinside.com 2019 - 2024. All rights reserved.