Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Redirect in Web Api Controller (HTTP 302 Found)

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.

like image 986
Chris Avatar asked Nov 02 '16 17:11

Chris


People also ask

Does a 302 automatically redirect?

What is an HTTP 302? The 302 status code is a redirection message that occurs when a resource or page you're attempting to load has been temporarily moved to a different location. It's usually caused by the web server and doesn't impact the user experience, as the redirect happens automatically.

How do I fix status code 302?

You can follow these five steps to fix HTTP 302 errors on your website: Determine whether the redirects are appropriate or not by examining the URLs that are issuing the 302 redirects. Check your plugins to make sure any redirect settings are valid. Ensure that your WordPress URL settings are configured correctly.

How does a 302 redirect work?

A 302 redirect does not pass the “juice,” or keep your domain authority to its new location. It simply redirects the user to the new location for you so they don't view a broken link, a 404 not found page, or an error page.

How we can redirect to another page or controller?

Redirect() method The first method od redirecting from one URL to another is Redirect(). The Rediect() method is available to your controller from the ControllerBase class. It accepts a target URL where you would like to go.


1 Answers

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));
}
like image 180
Rafael Marques Avatar answered Sep 30 '22 05:09

Rafael Marques