.NET HttpClient. Come POST valore stringa?


174

Come posso creare usando C # e HttpClient la seguente richiesta POST: User-Agent: Fiddler Tipo di contenuto: application / x-www-form-urlencoded Host: localhost: 6740 Lunghezza contenuto: 6

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

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

1
Quale client HTTP stai usando nell'immagine?
— zolfo


1
Il servizio è Web Api MVC. Formato JSON per richiesta?
— Kiquenet,

Risposte:


433
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, il mio HttpClientExtensions non ha un tale sovraccarico ... uso framework 4.0
— Ievgen Martynov

1
Quale sovraccarico non hai? Assicurati di aver installato Microsoft.AspNet.WebApi.ClientNuGet sul tuo progetto. La HttpClientclasse è costruita in .NET 4.5, non in .NET 4.0. Se si desidera utilizzarlo in .NET 4.0, è necessario NuGet!
— Darin Dimitrov

1
Primo SSSCE C # che ho incontrato. Come se fosse un gioco da ragazzi farlo funzionare se provieni da una lingua con un IDE adeguato.
— Buffalo,

13
Solo una nota che l'uso di HttpClient nell'uso dell'istruzione è un errore
— ren

26
Dovresti solo statico privato HttpClient _client = new HttpClient (); invece aspnetmonsters.com/2016/08/2016 08-27-27
— Sameer Alibhai

35

Di seguito è riportato un esempio per chiamare in modo sincrono, ma puoi facilmente passare ad asincronizzare usando wait-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)
{
}

1
Non penso che funzionerà. dovresti sostituire "login" con una stringa vuota, dovrebbe essere KeyValuePair <string, string> ("", "abc"), vedi la risposta accettata.
— Joedotnot non è il

questo funziona per me, lavoro su webservice php che sta chiamando $ company_id = $ _POST ("company_id"); come quello. Se invio come json, php non può funzionare.
— teapeng

8

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 della sezione POST dell'articolo

Il codice seguente invia una richiesta POST che contiene un'istanza del 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;
}

La richiesta è codificata in forma quindi non credo che JSON funzionerà
— ChrisFletcher,

È codificato in forma . Ad ogni modo, il formato JSON per le DateTimeproprietà? problemi di serializzazione?
— Kiquenet,

4
Non mi sembra di notare il tuo metodo "PostAsJsonAsync" Non è disponibile nella mia istanza di HttpClient.
— Tommy Holman,

4

Qui ho trovato questo articolo che è inviare la richiesta di post utilizzando JsonConvert.SerializeObject()e StringContent()ai HttpClient.PostAsyncdati

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

1

Potresti fare qualcosa del genere

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 quindi strReponse dovrebbe contenere i valori restituiti dal tuo servizio web


25
La domanda qui era su come usare il nuovo HttpCliente non il vecchio WebRequest.
— Darin Dimitrov

Vero non me ne sono accorto, lascerò comunque il posto nel caso qualcuno avesse bisogno di quello vecchio ...
— Axel
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.