Reputation: 27394
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
.
Upvotes: 13
Views: 16421
Reputation: 9864
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.
Upvotes: 0
Reputation: 355
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());
}
Upvotes: 0
Reputation: 1874
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));
}
Upvotes: 23