如何使用 C# 和 HttpClient 创建以下 POST 请求:
我的 WEB API 服务需要这样的请求:
[ActionName("exist")]
[HttpPost]
public bool CheckIfUserExist([FromBody] string login)
{
return _membershipProvider.CheckIfExist(login);
}
Microsoft.AspNet.WebApi.Client
NuGet 包):
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()
{
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轻松更改为异步:
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)
{
}
在这里我发现这篇文章是使用
JsonConvert.SerializeObject()
和StringContent()
发送帖子请求到HttpClient.PostAsync
数据
static async Task Main(string[] args)
{
var person = new Person();
person.Name = "John Doe";
person.Occupation = "gardener";
var json = Newtonsoft.Json.JsonConvert.SerializeObject(person);
var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
var url = "https://httpbin.org/post";
using var client = new HttpClient();
var response = await client.PostAsync(url, data);
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
这里是如何使用asp.net调用api的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 应包含您的网络服务返回的值