Use RedirectToAction in Web API

Thilok Gunawardena picture Thilok Gunawardena · Jul 31, 2012 · Viewed 32k times · Source

I am using RedirectToAction in my ASP.Net WebAPI application and I tried the following one.

return RedirectToAction("AuthenticateUser", "AuthenticationServiceWebApi", new RouteValueDictionary
                                                                    {
                                                                        {"userName", model.UserName},
                                                                        {"password", model.Password}
                                                                    });

This generates the redirection as below.

127.0.0.1:81/authenticationservicewebapi/authenticateuser/admin/admin@123

But, since I am using WebAPI, I need to be the URL like below.

127.0.0.1:81/api/authenticationservicewebapi/authenticateuser/admin/admin@123

How do I do this?

Answer

Aliostad picture Aliostad · Jul 31, 2012

If the user is not authenticated you should not redirect. There usually is no interactive user at the other end so you should really return HTTP Status Code 401 instead of redirect.


There is no equivalent in ASP.NET Web API.

If you insist doing it then here it is:

You throw HttpResponseException:

var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Found);
httpResponseMessage.Headers.Location = new Uri(myAddress, UriKind.Relative);
throw new HttpResponseException(httpResponseMessage);