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

时间:2012-03-16 14:32:45

标签: c# asp.net-mvc web-services

我正在使用c#控制器作为网络服务。

在其中我想将用户重定向到外部网址。

我该怎么做?

尝试:

System.Web.HttpContext.Current.Response.Redirect

但它不起作用。

3 个答案:

答案 0 :(得分:115)

使用Controller的Redirect()方法。

public ActionResult YourAction()
{
    // ...
    return Redirect("http://www.example.com");
}

<强>更新

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

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

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

答案 1 :(得分:10)

试试这个:

return Redirect("http://www.website.com");

答案 2 :(得分:9)

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

public ActionResult Index() {
        return new RedirectResult("http://www.website.com");
    }

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