如何对Web Api Action进行调用?

时间:2013-04-18 15:21:50

标签: c# asp.net asp.net-web-api

我已经创建了一个Web API Action,如下所示

[HttpPost]
public void Load(string siteName, string providerName, UserDetails userDetails)
{
// implementation
}

我注册的路线如下(不确定它是否正确?):

 config.Routes.MapHttpRoute(
             name: "loadUserDetails",
             routeTemplate: "sites/{siteName}/User/Load/{providerName}/{userDetailsList}",
             defaults: new
             {
                 controller = "User",
                 action = "Load",
                 providerName = UrlParameter.Optional
             });

providerName参数应该是可选的,我正在使用Xml序列化。

该操作应响应以下网址示例:

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]

如何对此操作进行调用以便我可以测试我的服务?

3 个答案:

答案 0 :(得分:3)

来自: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();

答案 1 :(得分:0)

如果您的问题是如何测试您的操作,则可以使用Fidler

请参阅http://www.mehdi-khalili.com/fiddler-in-action/part-2

答案 2 :(得分:0)

使用RestSharp和Web Request查看此处的响应:

http://pooyakhamooshi.blogspot.co.uk/2013/04/how-to-post-request-to-web-api-web.html