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

问题描述 投票:0回答:5

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

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

[ActionName("exist")]
[HttpPost]
public bool CheckIfUserExist([FromBody] string login)
{           
    return _membershipProvider.CheckIfExist(login);
}
c# asp.net-web-api dotnet-httpclient
5个回答
492
投票

在 ASP.NET 4.5 中(对于 4.0,您需要安装

Microsoft.AspNet.WebApi.Client
NuGet 包):

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

41
投票

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

29
投票

在这里我发现这篇文章是使用

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

9
投票

这里是如何使用asp.net调用api的POST部分的一小部分:

以下代码发送包含 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;
}

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 应包含您的网络服务返回的值

© www.soinside.com 2019 - 2024. All rights reserved.