如何使用C#和HTTPClient创建以下帖子请求: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);
}

答案

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

来自: stackoverflow.com