.NET HttpClient。 如何POSTstring值?

我如何创build使用C#和HttpClient下面的POST请求: User-Agent:Fiddler内容类型:application / x-www-form-urlencoded主机:localhost:6740内容长度:6

我需要这样一个请求我的WEB API服务:

[ActionName("exist")] [System.Web.Mvc.HttpPost] public bool CheckIfUserExist([FromBody] string login) { bool result = _membershipProvider.CheckIfExist(login); return result; } 
 using System; using System.Collections.Generic; using System.Net.Http; class Program { static void Main(string[] args) { Task.Run(() => MainAsync()); Console.ReadLine(); } static async Task MainAsync() { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:6740"); var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("", "login") }); var result = await client.PostAsync("/api/Membership/exists", content); string resultContent = await result.Content.ReadAsStringAsync(); Console.WriteLine(resultContent); } } } 

以下是同步调用的示例,但可以使用await-sync轻松更改为asynchronous:

 var pairs = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("login", "abc") }; var content = new FormUrlEncodedContent(pairs); var client = new HttpClient {BaseAddress = new Uri("http://localhost:6740")}; // call sync var response = client.PostAsync("/api/membership/exist", content).Result; if (response.IsSuccessStatusCode) { } 

在asp.net的网站上有一篇关于你的问题的文章。 我希望它可以帮助你。

如何调用一个ASPnetworking的API

http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

这里是文章POST部分的一小部分

以下代码将以JSON格式发送包含Product实例的POST请求:

 // HTTP POST var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" }; response = await client.PostAsJsonAsync("api/products", gizmo); if (response.IsSuccessStatusCode) { // Get the URI of the created resource. Uri gizmoUrl = response.Headers.Location; } 

你可以做这样的事情

 HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:6740/api/Membership/exist"); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = 6; StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII); streamOut.Write(strRequest); streamOut.Close(); StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()); string strResponse = streamIn.ReadToEnd(); streamIn.Close(); 

然后strReponse应该包含你的web服务返回的值