首页 > 解决方案 > 为什么在使用 Postman 工作时使用 C# HttpClient 调用 WebAPI 返回 401?

问题描述

这是 WebAPI 端点: https ://mysoylplus-apptest.frontierag.co.uk/api/someendpoint

我在 Postman 中以键值对形式发送 formData,如下所示:

authenticationData[b64EncryptedSoylSenseInfo] : 'somekey', authenticationData[b64iv] : 'some key'

上面的东西在 Postman 中工作,但是当我HttpClient在 C# 代码中使用时,这给了我401 exception.

我究竟做错了什么?我使用 Postman 得到 200 OK,但使用下面的代码得到 401。

string url = "https://mysoylplus-apptest.frontierag.co.uk/api/someendpoint";
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("Accept", "application/x-www-form-urlencoded");                



    using (var httpContent = new HttpRequestMessage(HttpMethod.Post, url))
    {
        client.Timeout = TimeSpan.FromMinutes(20);

        var values = new Dictionary<string, string>();   

        values.Add("authenticationData[b64EncryptedSoylSenseInfo]", "somekey");
        values.Add("authenticationData[b64iv]", "somekey");


        httpContent.Content = new FormUrlEncodedContent(values);

        var response = client.PostAsync(url, httpContent.Content);

        // here is the hash as string
        var result = response.Result.ToString();
    }
}

标签: c#restpostasp.net-web-apidotnet-httpclient

解决方案


推荐阅读