2013-03-02 85 views
120

如何创建使用C#和HttpClient的以下POST请求: User-Agent: Fiddler Content-type: application/x-www-form-urlencoded Host: localhost:6740 Content-Length: 6.NET HttpClient。如何POST字符串值?

我需要为我的Web API服务这样的要求:

[ActionName("exist")] 
[System.Web.Mvc.HttpPost] 
public bool CheckIfUserExist([FromBody] string login) 
{   
    bool result = _membershipProvider.CheckIfExist(login); 
    return result; 
} 
+0

您在图像中使用了哪个HTTP客户端? – brimstone 2016-02-10 18:37:19

+0

http://www.telerik.com/fiddler – 2016-02-11 17:40:22

+0

该服务是Web Api MVC。 *** JSON格式***请求? – Kiquenet 2018-02-23 08:45:33

回答

328
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); 
     } 
    } 
} 
+1

嗯,我的HttpClientExtensions没有这样的过载...我使用框架4.0 – 2013-03-02 16:42:17

+1

哪些超载你没有?确保你的项目已经安装了['Microsoft.AspNet.WebApi.Client'](http://nuget.org/packages/Microsoft.AspNet.WebApi.Client/)NuGet。 “HttpClient”类是在.NET 4.5中构建的,而不是在.NET 4.0中构建的。如果你想在.NET 4.0中使用它,你需要NuGet! – 2013-03-02 16:42:31

+1

我遇到了第一个C#SSSCE。好像如果你使用适当的IDE来自语言,就能轻松运行它。 – Buffalo 2015-04-01 06:12:21

29

下面是例如同步调用,但你可以很容易地改变使用的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) 
{ 
} 
2

你可以做这样的事情

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服务

+20

这里的问题是关于如何使用新的'HttpClient'而不是旧的'WebRequest'。 – 2013-03-02 16:26:45

+0

真的我没有注意到,我会离开帖子,以防有人需要旧的... – Axel 2013-03-02 16:48:48

4

回到那里是关于asp.net网站你的问题的文章。我希望它能帮助你。

如何调用的API与ASP净

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

这是一小部分从文章

后段下面的代码发送包含在产品中实例的POST请求JSON格式:

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

请求是表单urlencoded,所以我不认为JSON会工作 – ChrisFletcher 2017-08-31 09:44:47

+0

它是* form-urlencoded *。无论如何,***日期时间属性的JSON格式***?序列化问题? – Kiquenet 2018-02-23 08:44:17

+0

我似乎没有注意到你的方法“PostAsJsonAsync”这是不提供我HttpClient的实例。 – 2018-03-01 22:14:57