Use Redirect in Web Api Controller (HTTP 302 Found)

Chris picture Chris · Nov 2, 2016 · Viewed 10.4k times · Source

For some reason I am having lots of trouble trying to find out how to redirect (HTTP 302 Found) to an absolute URL from within a controller.

I have tried this:

this.Redirect("/assets/images/avatars/profile.jpg");

But I get an exception thrown

Exception thrown: 'System.UriFormatException' in System.dll

Additional information: Invalid URI: The format of the URI could not be determined.

Every other answer I see on here doesn't seem to be available to me. I am using Web API and MVC 5.

Answer

Rafael Marques picture Rafael Marques · Nov 2, 2016

With Redirect, you need to send a valid URI. In your case, if you want to return only the relative URI, you must tell it to URI class:

public IHttpActionResult Get()
{
    return Redirect(new Uri("/assets/images/avatars/profile.jpg", UriKind.Relative));
}