How to make a post call to a Web Api Action?

。_饼干妹妹 提交于 2020-01-04 08:08:10

问题


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

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