使用 HttpResponse.Redirect 重定向到新的 url C# MVC

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19294568/
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-10 14:40:07  来源:igfitidea点击:

Redirect to new url C# MVC with HttpResponse.Redirect

c#asp.net-mvc

提问by Niko

I am struggling with the HttpResponse.Redirectmethod. I thought it would be included in System.Webbut I am getting the

我正在努力使用该HttpResponse.Redirect方法。我以为它会被包括在内,System.Web但我得到了

The name 'Response' does not exist in the current context" error.

当前上下文中不存在名称“响应””错误。

This is the entire controller:

这是整个控制器:

using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;

namespace MvcApplication1.Controllers
{
    public class SmileyController : ApiController
    {
        public HttpResponseMessage Get(string id)
        {
            Response.Redirect("http://www.google.com");
            return new HttpResponseMessage
            {
                Content = new StringContent("[]", new UTF8Encoding(), "application/json"),
                StatusCode = HttpStatusCode.NotFound,
            };
        }
    }
}

采纳答案by Aleksei Chepovoi

You can get HttpResponse object for current request in Your action method using the following line:

您可以使用以下行在您的操作方法中获取当前请求的 HttpResponse 对象:

HttpContext.Current.Response

and so You can write:

所以你可以写:

HttpContext.Current.Response.Redirect("http://www.google.com");  

Anyway, You use HttpResponseMessage, so the proper way to redirect would be like this:

无论如何,您使用 HttpResponseMessage,因此重定向的正确方法是这样的:

public HttpResponseMessage Get(string id)
{
    // Your logic here before redirection

    var response = Request.CreateResponse(HttpStatusCode.Moved);
    response.Headers.Location = new Uri("http://www.google.com");
    return response;
}

回答by Tom Bowers

In an MVC web application controller, Response isn't accessed in the same way as it would be from an aspx page. You need to access it through the current http context.

在 MVC Web 应用程序控制器中,访问 Response 的方式与从 aspx 页面访问的方式不同。您需要通过当前的 http 上下文访问它。

HttpContext.Current.Response.Redirect("http://www.google.com");

回答by Natan

Set the Headers.Locationproperty in your HttpResponseMessageinstead.

Headers.Location在您的属性中设置属性HttpResponseMessage