2013-03-02 11 views
120

Come posso creare utilizzando C# e HttpClient la seguente richiesta POST: User-Agent: Fiddler Content-type: application/x-www-form-urlencoded Host: localhost:6740 Content-Length: 6HttpClient .NET. Come calcolare il valore della stringa POST?

ho bisogno di una tale richiesta per il mio servizio WEB API:

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

Quale client HTTP si sta utilizzando nell'immagine? – brimstone

+0

http://www.telerik.com/fiddler –

+0

Il servizio è Web Api MVC. *** Formato JSON *** per richiesta? – Kiquenet

risposta

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

hm, le mie HttpClientExtensions non hanno tale sovraccarico ... io uso framework 4.0 –

+1

Quale sovraccarico non hai? Assicurati di aver installato il ['Microsoft.AspNet.WebApi.Client'] (http://nuget.org/packages/Microsoft.AspNet.WebApi.Client/) NuGet nel tuo progetto. La classe 'HttpClient' è costruita in .NET 4.5, non in .NET 4.0. Se vuoi usarlo in .NET 4.0 hai bisogno di NuGet! –

+1

Primo C# SSSCE Mi capita. Come se fosse una tale brezza farlo funzionare se vieni da una lingua con un IDE adeguato. – Buffalo

29

Di seguito è esempio per chiamare in modo sincrono, ma si può facilmente cambiare a ASYNC utilizzando 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) 
{ 
} 
2

Si potrebbe fare qualcosa di simile

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

E poi strReponse dovrebbe contenere i valori restituiti dal vostro webservice

+20

La domanda qui era su come usare il nuovo 'HttpClient' e non il vecchio' WebRequest'. –

+0

Vero che non l'ho notato, lascerò comunque il post nel caso qualcuno abbia bisogno del vecchio ... – Axel

4

C'è un articolo sulla tua domanda sul sito web di asp.net. Spero possa aiutarti.

Come chiamare un'API con asp net

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

Ecco una piccola parte dalla sezione POST dell'articolo

Il codice seguente invia una richiesta POST che contiene un'istanza di prodotto in Formato 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

La richiesta è form-urlencoded quindi non credo che JSON funzionerà – ChrisFletcher

+0

È * form-urlencoded *. Comunque, *** Formato JSON *** per le proprietà 'DateTime'? problemi di serializzazione? – Kiquenet

+0

Non sembra che noti il ​​tuo metodo "PostAsJsonAsync" Non è disponibile nella mia istanza HttpClient. –

Problemi correlati