如何创建使用C#和HttpClient的以下POST请求:
我需要为我的Web API服务这样的要求:
[ActionName("exist")]
[System.Web.Mvc.HttpPost]
public bool CheckIfUserExist([FromBody] string login)
{
bool result = _membershipProvider.CheckIfExist(login);
return result;
}
如何创建使用C#和HttpClient的以下POST请求:
我需要为我的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同步更改为异步:
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网站你的问题的文章。 我希望它可以帮助你。
如何调用与ASP网的API
http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
这是一小部分从文章后段
下面的代码发送一个包含一个JSON格式的产品实例的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服务返回的值