13

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.

asked Nov 2, 2016 at 17:50
1

3 Answers 3

23

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));
}
answered Nov 2, 2016 at 20:49

Comments

0

In .NET Core 2.1, and probably lower version of .NET Core, you cannot pass in a Uri. So you have to create the Uri and call the .ToString() method.

Like so.

 [HttpGet]
 public IActionResult Get()
 {
 Uri url = new Uri("../Path/To/URI", UriKind.Relative);
 return Redirect(url.ToString());
 }
answered Aug 7, 2018 at 13:36

Comments

0

This is some non sense shortcoming from my viewpoint. The .Net Framework Web Api Redirect method does not support getting an uri path string as a location.

So you have to do as this answer tells.

But rather than doing that every time you have to redirect, it is better to fix that API:

/// <inheritdoc />
protected override RedirectResult Redirect(string location)
{
 // The original version just crash on location not supplying the server name,
 // unless who asked it to please consider the possibility you do not wish to tell
 // it every time you have a redirect to "self" to do.
 return base.Redirect(new Uri(location, UriKind.RelativeOrAbsolute));
}

I am putting this in my base controller, and so can forget about this shortcoming.

answered Oct 15, 2020 at 22:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.