如何从 c# 控制器重定向到外部 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9739170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:38:53  来源:igfitidea点击:

how to redirect to external url from c# controller

c#asp.net-mvcweb-services

提问by Elad Benda

I'm using a c# controller as web-service.

我使用 ac# 控制器作为网络服务。

In it I want to redirect the user to an external url.

在其中,我想将用户重定向到外部 url。

How do I do it?

我该怎么做?

Tried:

尝试:

System.Web.HttpContext.Current.Response.Redirect

but it didn't work.

但它没有用。

采纳答案by jrummell

Use the Controller's Redirect()method.

使用控制器的Redirect()方法。

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

Update

更新

You can't directly perform a server side redirect from an ajax response. You could, however, return a JsonResult with the new url and perform the redirect with javascript.

您不能直接从 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;
});

回答by Tom Chantler

Try this:

尝试这个:

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

回答by EndlessSpace

If you are using MVC then it would be more appropriate to use RedirectResultinstead of using Response.Redirect.

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

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

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

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