.NET HttpClient. How to POST string value?

2019-01-01 05:09发布

问题:

How can I create using C# and HttpClient the following POST request: \"User-Agent:

I need such a request for my WEB API service:

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

回答1:

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


回答2:

Below is example to call synchronously but you can easily change to async by using 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)
{
}


回答3:

There is an article about your question on asp.net\'s website. I hope it can help you.

How to call an api with asp net

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

Here is a small part from the POST section of the article

The following code sends a POST request that contains a Product instance in JSON format:

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


回答4:

You could do something like this

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

And then strReponse should contain the values returned by your webservice