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

2019-07-14 07:20发布

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?

3条回答
何必那么认真
2楼-- · 2019-07-14 07:44

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();
查看更多
贪生不怕死
3楼-- · 2019-07-14 07:48

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

查看更多
smile是对你的礼貌
4楼-- · 2019-07-14 08:04

If your question is how to test your action, you can use Fidler.

See http://www.mehdi-khalili.com/fiddler-in-action/part-2

查看更多
登录 后发表回答