【问题标题】:HttpClient sending parameter nullHttpClient发送参数null
【发布时间】:2018-02-08 15:33:02
【问题描述】:

我正在尝试使用 HttpClient 向 api 发送数据,但我发送的参数一直为 0。

我在这里做错了什么?这是我第一次使用 HttpClient,所以很可能是我把事情弄混了或者犯了一些菜鸟的错误。

路径正确,我可以从 Postman 获取结果。

我正在使用的代码是这样的;

static async Task GetActivityList()
{
    string uri = "/api/ExtraNet/GetActivityList";

    HttpClient client = new HttpClient();

    int SalesPersonId = 553;
    string token = my token value is here;

    client.BaseAddress = new Uri("http://localhost:16513/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var postData = "{\"SalesPersonId=\":\""+SalesPersonId+"\"}";
    var stringContent = new StringContent( "{\"SalesPersonId=\":\"" + SalesPersonId + "\"}", Encoding.UTF8, "application/json") ;
    var content = new StringContent(postData, Encoding.UTF8, "application/json");

    var response = await client.PostAsync("http://localhost:16513/api/ExtraNet/GetActivityList", stringContent);
    var result = await response.Content.ReadAsStringAsync();
    Console.WriteLine(result);
}

【问题讨论】:

  • 为什么要创建 postData 和 content?
  • 在尝试不同的方式发送参数时可能未对其进行注释

标签: c# dotnet-httpclient


【解决方案1】:

我设法以这种方式发送参数

string uri = "/api/ExtraNet/GetActivityList";

            HttpClient client = new HttpClient();

            int SalesPersonId = 553;
            string token = "";

            client.BaseAddress = new Uri("http://localhost:16513/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            var stringContent = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string,string>("SalesPersonId","553")
            });

            var response = await client.PostAsync(uri, stringContent);
            var result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);

FormUrlEncodedContent 发送参数就可以了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2013-06-03
    • 2019-08-18
    相关资源
    最近更新 更多