Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use RedirectToAction in Web API

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?

like image 326
Thilok Gunawardena Avatar asked Jul 31 '12 09:07

Thilok Gunawardena


2 Answers

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);
like image 178
Aliostad Avatar answered Sep 19 '22 09:09

Aliostad


I'm not sure how your routing, Web API action signature look like so I will try to guess. A few things don't really add up here (why would you pass the password in the url?)

but...

Given your url structure I'd guess your routing is something like:

    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}/{id2}",
        defaults: new { id = RouteParameter.Optional, id2 = RouteParameter.Optional }
    );

Then given that, I guess your authenticateuser must be something like:

public HttpResponseMessage AuthenticateUser([FromUri]string id, [FromUri]string id2)

If so, then to redirect to this from an MVC controller you need:

        return Redirect(
            Url.RouteUrl("DefaultApi", 
                new { httproute = "", 
                      controller = "AuthenticationServiceWebApi", 
                      action = "AuthenticateUser", 
                      id = model.UserName,
                      id2 = model.Password
            }));
like image 38
Filip W Avatar answered Sep 20 '22 09:09

Filip W