问题
I've created a Web API Action as below
[HttpPost]
public void Load(string siteName, string providerName, UserDetails userDetails)
{
// implementation
}
The route I've registered for this is as below (not sure if it's correct?):
config.Routes.MapHttpRoute(
name: "loadUserDetails",
routeTemplate: "sites/{siteName}/User/Load/{providerName}/{userDetailsList}",
defaults: new
{
controller = "User",
action = "Load",
providerName = UrlParameter.Optional
});
The providerName parameter should be optional and I'm using Xml Serialization.
The action should response to the below url sample:
http://www.domain.com/sites/site1/user/load/provider1/[some user details in the post]
or
http://www.domain.com/sites/site1/user/load/[some user details in the post]
How could I make a post call to this action so that I can test my service?
回答1:
From: HTTP request with post
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(@"http:\\domain.com\page.asp");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=user";
postData += "&password=pass";
byte[] data = encoding.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data,0,data.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
回答2:
If your question is how to test your action, you can use Fidler.
See http://www.mehdi-khalili.com/fiddler-in-action/part-2
回答3:
See the response from here using RestSharp and Web Request:
http://pooyakhamooshi.blogspot.co.uk/2013/04/how-to-post-request-to-web-api-web.html
来源:https://stackoverflow.com/questions/16086903/how-to-make-a-post-call-to-a-web-api-action