Redirecting to a new C # MVC URL with HttpResponse.Redirect

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

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

This is the whole 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, }; } } } 
+6
source share
3 answers

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

 HttpContext.Current.Response 

and therefore you can write:

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

Anyway, you are using HttpResponseMessage, so the correct redirection method would be as follows:

 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; } 
+18
source

In a web application controller, MVC Response does not gain access in the same way as in an aspx page. You need to access it through the current http context.

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

Set the Headers.Location property to HttpResponseMessage .

+1
source

Source: https://habr.com/ru/post/955661/


All Articles