94

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.

10
  • I don't think you can do that - it's a cross-domain security violation. Commented Mar 16, 2012 at 14:35
  • How are consumers consuming the web service? Commented Mar 16, 2012 at 14:35
  • Define "as web-service." How is the controller action being accessed? You can send a redirect response, but if that response isn't going to a standard web browser request then it'll probably be ignored. Commented Mar 16, 2012 at 14:36
  • 1
    @EladBenda: I'm not sure what a 324 error actually means. I suspect that a JavaScript redirect should also contain the http:// segment of the URL, though. Commented Mar 16, 2012 at 18:12
  • 1
    possible duplicate of .net mvc redirect to external url Commented Feb 12, 2015 at 18:24

3 Answers 3

174

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;
});
Sign up to request clarification or add additional context in comments.

6 Comments

I was happy too soon. still doesn't work. I'm calling it from ajax POST.
Are you trying to redirect the entire page or just the ajax response?
is there really a way to create anonymus type like you did? (new {url: "example.com"})
Wrong syntax, sorry. It should be new {url = "example.com"}.
@dipievil the javascript should be placed in your view.
|
25

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/

1 Comment

Perfect - beats RedirectToPage
16

Try this:

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

2 Comments

note, you cannot use "www.website.com" - you must provide the http:// or https:// syntax
Thank you @markthewizard1234 among all the answers ive browsed, your note was the one thing that set it straight for me. I did not give it a thought as i was using a dynamic redirect to intranet sites.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.