Santanu Bhattacharjee
Santanu Bhattacharjee

Reputation: 29

how to use response.redirect in webapi+asp.net?

I want to redirect to another .aspx page from WebAPI. I have used this code but it is not working:

string url = "http://localhost:61884/UserList.aspx";
System.Uri uri = new System.Uri(url);
return Redirect(uri).ToString();

Upvotes: 0

Views: 1697

Answers (3)

Igor
Igor

Reputation: 62213

You don't. (or your description of the problem is not accurate)

Web API is meant to retrieve data or persist data, it is a way to interact with the server from the client without having to do the traditional form post or page request calls. The caller (javascript based on your question tag angularJs) needs to execute the redirect once the results from the call to the Web API are retrieved.

  • This is good SOC (separation of concerns), the business logic in the Web API should not care about routes (angularjs) / web pages.
  • Even if you wanted to the Web API, because of how its called, can't redirect the client.

Summary: The Web API code itself should not any type of redirecting of the client. The client should handle this.


Sample call to web api and redirect from angular code:

$http({
    url: "/api/SomeWebApiUrl",
    data: {},
    method: "POST",
    headers: { 'Content-Type': "application/json" },
    responseType: "json"
}).then(function (response) {
    if(response.data.somethingToCheck === someConditionThatWarrentsRedirect)
        $window.location.href = "~/someOtherUrl/";
});

Upvotes: 2

perkes456
perkes456

Reputation: 1181

try something like this:

var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);

Hope that helps.

Upvotes: 0

Dylan
Dylan

Reputation: 1118

Redirect from asp.net web api post action

public HttpResponseMessage Post()
{
   // ... do the job

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

Upvotes: -1

Related Questions