Use RedirectToAction in Web API

谁说我不能喝 提交于 2019-12-04 05:22:05

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
            }));
Aliostad

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);

I also came up with a simple solution. Not very good as the above, but worth sharing.

        string post_data = "userName=th&password=admin@123";

        string uri = "http://127.0.0.1:81/api/authenticationservicewebapi/authenticateuser";

        // create a request
        HttpWebRequest request = (HttpWebRequest)
        WebRequest.Create(uri); 
        request.KeepAlive = false;
        request.ProtocolVersion = HttpVersion.Version10;
        request.Method = "POST";

        // turn our request string into a byte stream
        byte[] postBytes = Encoding.ASCII.GetBytes(post_data);

        // this is important - make sure you specify type this way
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postBytes.Length;
        Stream requestStream = request.GetRequestStream();

        // now send it
        requestStream.Write(postBytes, 0, postBytes.Length);
        requestStream.Close();

Thank You all.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!