8

I am struggling with the HttpResponse.Redirect method. I thought it would be included in System.Web but I am getting the

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,
 };
 }
 }
}
Roman Marusyk
24.8k27 gold badges82 silver badges127 bronze badges
asked Oct 10, 2013 at 11:28
2

3 Answers 3

23

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

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:

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;
}
answered Oct 10, 2013 at 11:42

2 Comments

Why isnt the HttpStatusCode.Redirect used?
@Martea HttpStatusCode.Redirect is a temporary redirect. HttpStatusCode.Moved indicates the redirect is permanent.
1

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.

HttpContext.Current.Response.Redirect("http://www.google.com");
answered Oct 10, 2013 at 11:34

Comments

0

Set the Headers.Location property in your HttpResponseMessage instead.

Roman Marusyk
24.8k27 gold badges82 silver badges127 bronze badges
answered Oct 10, 2013 at 11:34

1 Comment

He needs to also change the status code to 301 or 302 rather than 404.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.