Use Redirect in Web Api Controller (HTTP 302 Found)

ⅰ亾dé卋堺 提交于 2020-05-14 16:52:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!