【问题标题】:Use Redirect in Web Api Controller (HTTP 302 Found)在 Web Api 控制器中使用重定向(发现 HTTP 302)
【发布时间】:2017-03-16 03:43:53
【问题描述】:
由于某种原因,我在尝试找出如何从控制器中将 (HTTP 302 Found) 重定向到绝对 URL 时遇到了很多麻烦。
我试过这个:
this.Redirect("/assets/images/avatars/profile.jpg");
但是我抛出了一个异常
抛出异常:System.dll 中的“System.UriFormatException”
附加信息:无效的 URI:无法确定 URI 的格式。
我在这里看到的所有其他答案似乎都对我不可用。我正在使用Web API 和MVC 5。
【问题讨论】:
标签:
c#
asp.net-mvc
redirect
asp.net-web-api
http-status-code-302
【解决方案1】:
从我的角度来看,这是一些毫无意义的缺点。 .Net Framework Web Api Redirect 方法不支持获取 uri 路径字符串作为位置。
所以你必须按照answer 所说的那样做。
但与其每次必须重定向时都这样做,不如修复该 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));
}
我将它放在我的基本控制器中,因此可以忘记这个缺点。
【解决方案2】:
在 .NET Core 2.1 以及可能更低版本的 .NET Core 中,您不能传入 Uri。所以你必须创建 Uri 并调用 .ToString() 方法。
像这样。
[HttpGet]
public IActionResult Get()
{
Uri url = new Uri("../Path/To/URI", UriKind.Relative);
return Redirect(url.ToString());
}
【解决方案3】:
使用Redirect,您需要发送有效 URI。在您的情况下,如果您只想返回relative URI,您必须告诉URI class:
public IHttpActionResult Get()
{
return Redirect(new Uri("/assets/images/avatars/profile.jpg", UriKind.Relative));
}