重定向到新的网址 C# MVC with HttpResponse.Redirect

本文关键字:MVC with HttpResponse Redirect 重定向 | 更新日期: 2023-09-27 18:34:48

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

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

这是整个控制器:

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,
            };
        }
    }
}

重定向到新的网址 C# MVC with HttpResponse.Redirect

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

HttpContext.Current.Response

所以你可以写:

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

无论如何,您使用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;
}

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

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

改为在HttpResponseMessage中设置 Headers.Location 属性。