views:

55

answers:

3

Hello,

Does anybody know how to redirect to another server/solution using ASP.NET MVC? Something like this:

public void Redir(String param)
{
   // Redirect to another application, ie:
   // Redirect("www.google.com");
   // or
   // Response.StatusCode= 301;
   // Response.AddHeader("Location","www.google.com");
   // Response.End();

}

I´ve tried both ways above, but it doesn´t work.

+1  A: 
    public ActionResult Redirect()
    {
        return new RedirectResult("http://www.google.com");
    }

hope this helps :-)

WestDiscGolf
+1  A: 

The RedirectResult will give you a 302, however if you need a 301 use this result type:

public class PermanentRedirectResult : ActionResult
{
    public string Url { get; set; }

    public PermanentRedirectResult(string url)
    {
        if (string.IsNullOrEmpty(url))
        {
            throw new ArgumentException("url is null or empty", "url");
        }
        this.Url = url;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        context.HttpContext.Response.StatusCode = 301;
        context.HttpContext.Response.RedirectLocation = Url;
        context.HttpContext.Response.End();
    }
} 

Then use it like mentioned above:

public PermanentRedirectResult Redirect()
{
    return new RedirectResult("http://www.google.com");
}

Source (as it's not my work): http://forums.asp.net/p/1337938/2700733.aspx

amarsuperstar
+1 for adding the source from where you got it. I can appreciate such act.
XIII
A: 

Thanks for the answer but, I´ve tryed this last solution (from amarsuperstar) and it doesn't work for my app. The browser sends a "POST" to the Redirect method, recived a StatusCode 301, the location is correct ("www.google.com"), but the browser sends a GET to "http://localhost:9090/MyApp/MyController/www.google.com" and recive a 404. Seems it´s trying to load the redirect url into my application path.

My Global.asax has a Default route: "{Controller}/{action}/{id}".

Should I create a new route for this redirection? Any ideas for solving it?

Thanks, André

André Schuster
Instead of replying make it a comment on on the reply itself. This is not a traditional forum.
XIII