问题
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
.
回答1:
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));
}
回答2:
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());
}
来源:https://stackoverflow.com/questions/40386554/use-redirect-in-web-api-controller-http-302-found