14

Is there a Web API controller method equivalent to the MVC controller method RedirectToAction? I would like to call one method from another, but retain the filter actions for the secondary method.

Eric
  • 1,737
  • 1
  • 13
  • 17
  • This might answer your question: http://stackoverflow.com/questions/16295597/asp-net-web-api-redirect-request – Dennis Traub Jun 27 '13 at 15:50
  • The different actions have different parameters. How would I be able to set the parameters on the secondary action using a header based redirect? Making a direct class call would not allow me to make use of the existing action filters. Or am I approaching this incorrectly? Should I instead be looking to custom routing, instead? – Eric Jun 27 '13 at 16:14

2 Answers2

30

Is there a Web API controller method equivalent to the MVC controller method RedirectToAction?

You could set the Location header:

public HttpResponseMessage Get()
{
    var response = Request.CreateResponse(HttpStatusCode.Found);
    response.Headers.Location = new Uri("http://www.google.com");
    return response;
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • The two actions have different parameters. How would I be able to set the values for the parameters for the secondary action using the header redirect? – Eric Jun 27 '13 at 16:21
  • Just use the `Url` helper: `response.Headers.Location = new Uri(Url.Action("SomeAction", "SomeController", new { foo = "bar" }));`. – Darin Dimitrov Jun 27 '13 at 17:01
  • This was very close to satisfying my needs. My case, however, requires the variable to be a POST. If that were not the case, this solution would prove very interesting (though WebAPI doesn't have Url.Action). Nonetheless, this is by far the best answer.... – Eric Jun 27 '13 at 20:58
6

You can check this for redirecting a page from a controller in web api

[Route("Report/MyReport")]
public async Task<IHttpActionResult> getReport() {

    string url = "https://localhost:44305/Templates/ReportPage.html";

    System.Uri uri = new System.Uri(url);

    return Redirect(uri);
}
Haroen Viaene
  • 1,329
  • 18
  • 33
Debendra Dash
  • 5,334
  • 46
  • 38