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

Iev*_*nov 165 c# asp.net-web-api dotnet-httpclient

如何使用C#和HttpClient创建以下POST请求: User-Agent:Fiddler内容类型:application/x-www-form-urlencoded主机:localhost:6740内容长度:6

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

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

Dar*_*rov 412

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你应该私有静态只读HttpClient _client = new HttpClient(); 而是https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ (24认同)
  • 只是注意在使用语句时使用HttpClient是一个[错误](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/) (12认同)

cuo*_*gle 32

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


Rav*_*ana 12

在这里我发现这篇文章这是使用发送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(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);
}
Run Code Online (Sandbox Code Playgroud)


one*_*end 6

在asp.net的网站上有一篇关于您的问题的文章。希望对您有所帮助。

如何用ASP NET调用API

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

这是本文的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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我似乎没有注意到您的方法“ PostAsJsonAsync”在我的HttpClient实例中不可用。 (2认同)