C# .NET HttpClient。如何POST字符串值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15176538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:21:29  来源:igfitidea点击:

.NET HttpClient. How to POST string value?

c#asp.net-web-apidotnet-httpclient

提问by Ievgen Martynov

How can I create using C# and HttpClient the following POST request: User-Agent: Fiddler Content-type: application/x-www-form-urlencoded Host: localhost:6740 Content-Length: 6

如何使用 C# 和 HttpClient 创建以下 POST 请求: User-Agent: Fiddler Content-type: application/x-www-form-urlencoded Host: localhost:6740 Content-Length: 6

I need such a request for my WEB API service:

我的 WEB API 服务需要这样的请求:

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

采纳答案by Darin Dimitrov

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

回答by cuongle

Below is example to call synchronously but you can easily change to async by using await-sync:

下面是同步调用的示例,但您可以使用 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)
{
}

回答by Axel

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

然后 strReponse 应包含您的网络服务返回的值

回答by oneNiceFriend

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

在asp.net 的网站上有一篇关于您的问题的文章。我希望它能帮助你。

How to call an api with asp net

如何使用asp net调用api

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

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

这是文章POST部分的一小部分

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

以下代码发送包含 JSON 格式的 Product 实例的 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;
}

回答by Ravi Makwana

HereI found this article which is send post request using JsonConvert.SerializeObject()& StringContent()to HttpClient.PostAsyncdata

在这里我发现这篇文章这是使用发送POST请求JsonConvert.SerializeObject()StringContent()HttpClient.PostAsync数据

static async Task Main(string[] args)
{
    var person = new Person();
    person.Name = "John Doe";
    person.Occupation = "gardener";

    var json = Newtonsoft.Json.JsonConvert.SerializeObject(param);
    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);
}