net HttpClient。如何POST字符串值?

如何使用c#和HttpClient创建以下POST请求: User-Agent: Fiddler Content-type: application/x-www-form-urlencoded Host: localhost:6740 Content-Length: 6

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

[ActionName("exist")]
[HttpPost]
public bool CheckIfUserExist([FromBody] string login)
{
return _membershipProvider.CheckIfExist(login);
}
504259 次浏览

下面是同步调用的例子,但你可以通过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)
{
}

你可以这样做

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();

然后strresponse应该包含webservice返回的值

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);
}
}
}

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

如何用asp net调用api

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

以下是本文POST部分的一小部分

下面的代码发送一个POST请求,其中包含一个JSON格式的Product实例:

// 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;
}

我发现这篇文章是使用JsonConvert.SerializeObject() &发送post请求;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);
}