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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (73)

如何使用C#和HttpClient创建以下POST请求:

对于我的WebAPI服务,我需要这样的请求:

[ActionName("exist")]
[System.Web.Mvc.HttpPost]
public bool CheckIfUserExist([FromBody] string login)
{           
    bool result = _membershipProvider.CheckIfExist(login);
    return result;
}
提问于
用户回答回答于
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);
        }
    }
}
用户回答回答于

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

扫码关注云+社区

领取腾讯云代金券