小编典典

.NET HttpClient。如何发布字符串值?

all

如何使用 C# 和 HttpClient 创建以下 POST 请求: 用户代理:提琴手内容类型:application/x-www-form-
urlencoded 主机:localhost:6740 内容长度:6

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

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

阅读 60

收藏
2022-07-02

共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);
        }
    }
}
2022-07-02