问题
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?
回答1:
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
}));
回答2:
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);
回答3:
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.
来源:https://stackoverflow.com/questions/11737040/use-redirecttoaction-in-web-api