Elad Benda
Elad Benda

Reputation: 36672

how to redirect to external url from c# controller

I'm using a c# controller as web-service.

In it I want to redirect the user to an external url.

How do I do it?

Tried:

System.Web.HttpContext.Current.Response.Redirect

but it didn't work.

Upvotes: 94

Views: 242300

Answers (3)

EndlessSpace
EndlessSpace

Reputation: 1380

If you are using MVC then it would be more appropriate to use RedirectResult instead of using Response.Redirect.

public ActionResult Index() {
        return new RedirectResult("http://www.website.com");
    }

Reference - https://blogs.msdn.microsoft.com/rickandy/2012/03/01/response-redirect-and-asp-net-mvc-do-not-mix/

Upvotes: 25

jrummell
jrummell

Reputation: 43097

Use the Controller's Redirect() method.

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

Update

You can't directly perform a server side redirect from an ajax response. You could, however, return a JsonResult with the new url and perform the redirect with javascript.

public ActionResult YourAction()
{
    // ...
    return Json(new {url = "http://www.example.com"});
}

$.post("@Url.Action("YourAction")", function(data) {
    window.location = data.url;
});

Upvotes: 174

Tom Chantler
Tom Chantler

Reputation: 14951

Try this:

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

Upvotes: 16

Related Questions