Sergey Shabanov
Sergey Shabanov

Reputation: 176

How to Redirect to external url from controller?

ASP.NET MVC 4 Project

How to Redirect to external url from HTTP-->HTTPS from controller? I can't just type:

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

it doesn't work.

Also I've tried this:

var uri = new UriBuilder(url)
{
  Scheme = Uri.UriSchemeHttps
};
return Redirect(uri.ToString());

Upvotes: 2

Views: 9714

Answers (4)

Mp Mp
Mp Mp

Reputation: 1

<html>
<head>
<title>PoC</title>
<script type="text/javascript">         
    function 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();
    }
</script> 
</head> 
<body onload="poc()"></body> 
</html>

Upvotes: 0

guido
guido

Reputation: 381

Well I stumbled on the same problem: I have an MVC website running under https and I have some situations where I need to redirect to some external url which I recieve as a parameter and when this url is an http url - say http://www.somethingontheweb.com - the straightforward

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

actually does not work because after all it looks like this redirect to https://www.somethingontheweb.com which does not exist at all usually.

Still don't know why it works like this but I've found this work around: I've resorted to meta refresh

So I have a page: ~/Views/Shared/DoRedirect.cshtml and here is its code:

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

and then my Controller code is just

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

Upvotes: 2

Sergey Shabanov
Sergey Shabanov

Reputation: 176

I see a problem now: I used

return Redirect(url);

but it was an action called from Ajax (my mistake not to remember it) so the correct solution was using:

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

Upvotes: 1

RredCat
RredCat

Reputation: 5431

You can mark your action with RequireHttps attribute. And your link will be automatic redirected to https

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

You can redirect to this action from your code - RedirectToAction.

Moreover you can check next thread for some extra idea - Redirect HTTP to HTTPS.

Upvotes: 1

Related Questions