如何从c#controller重定向到外部URL

Ela*_*nda 68 c# asp.net-mvc web-services

我正在使用ac#controller作为web服务.

在其中我想将用户重定向到外部URL.

我该怎么做?

尝试:

System.Web.HttpContext.Current.Response.Redirect
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

jru*_*ell 124

使用Controller的Redirect()方法.

public ActionResult YourAction()
{
    // ...
    return Redirect("http://www.example.com");
}
Run Code Online (Sandbox Code Playgroud)

更新

您无法直接从ajax响应执行服务器端重定向.但是,您可以使用新URL返回JsonResult并使用javascript执行重定向.

public ActionResult YourAction()
{
    // ...
    return Json(new {url = "http://www.example.com"});
}

$.post("@Url.Action("YourAction")", function(data) {
    window.location = data.url;
});
Run Code Online (Sandbox Code Playgroud)


Tom*_*ler 13

试试这个:

return Redirect("http://www.website.com");
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您不能使用"www.website.com" - 您必须提供http://或https://语法 (4认同)
  • 谢谢@ markthewizard1234在我浏览过的所有答案中,你的笔记是让我直截了当的一件事.我没有考虑,因为我使用动态重定向到Intranet站点. (2认同)

End*_*ace 10

如果您正在使用MVC,那么使用RedirectResult而不是使用Response.Redirect 更合适.

public ActionResult Index() {
        return new RedirectResult("http://www.website.com");
    }
Run Code Online (Sandbox Code Playgroud)

参考 - https://blogs.msdn.microsoft.com/rickandy/2012/03/01/response-redirect-and-asp-net-mvc-do-not-mix/