Use Redirect in Web Api Controller (HTTP 302 Found)
Asked Answered
H

3

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.

Home answered 2/11, 2016 at 17:50 Comment(1)
#11325211Likable
P
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));
}
Prefect answered 2/11, 2016 at 20:49 Comment(0)
R
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());
 }
Row answered 7/8, 2018 at 13:36 Comment(0)
H
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.

Hypochondriasis answered 15/10, 2020 at 22:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.