如何对Web Api动作进行post调用
本文关键字:post 调用 Web Api | 更新日期: 2023-09-27 18:09:47
我创建了一个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序列化。
动作应该响应下面的url示例:
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]
我如何对这个动作进行post调用,以便测试我的服务?
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();
如果你的问题是如何测试你的动作,你可以使用Fidler。
见http://www.mehdi-khalili.com/fiddler-in-action/part-2
查看此处使用RestSharp和Web Request的响应:
http://pooyakhamooshi.blogspot.co.uk/2013/04/how-to-post-request-to-web-api-web.html