使用 WebClient 调用授权的 Web API

Den*_*dić 6 api webclient token unauthorized http-status-code-401

经过几个小时的互联网搜索,我决定向你们寻求帮助。

我已经用几个简单的 get/post 方法编写了一个 Web API。我正在使用个人用户帐户身份验证方法。

使用 HttpClient,我成功地调用了每个 AUTHORIZED get 和 post 方法以及用于生成授权令牌的 /token 端点。

问题是我必须在 .NET Framework 3.5 项目中调用这些方法。因此,我尝试使用 WebClient 来执行此操作,因为我了解到 .NET Framework 3.5 不支持 HttpClient。

GetAPIToken() 方法生成不记名令牌并且它有效。

 private static string GetAPIToken(string userName, string password, string apiBaseUri)
    {
        using (WebClient client = new WebClient())
        {
            client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            var response = client.UploadString(apiBaseUri + "/Token", "POST", "grant_type=password&username=" + userName + "&password=" + password);
            var jObject = JObject.Parse(response);
            return jObject.GetValue("access_token").ToString();
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我从 Web API 中删除 [Authorize] 属性时,此 GET 方法有效,但在获得授权后无法使其工作。

    //GET ODRA?ENI POSTUPCI
    private static string GetOdradjeniPostupci(int Id, string token)
    {
        string apiBaseUri = "http://localhost:60511/";
        string serviceUrl = apiBaseUri + "api/ZOdradjeniPostupci";

        using (WebClient client = new WebClient())
        {
            client.Headers.Clear();
            client.Headers.Add("Content-Type", "application/json");
            client.Headers.Add("Authorization", "Bearer " + token);
            var response = client.DownloadString(serviceUrl + "/GetZOdradjeniPostupci?cZdrUst=" + Id.ToString());

            return response;
        }
    }
Run Code Online (Sandbox Code Playgroud)

无论我尝试什么,我都会收到未授权的错误 401。(来自互联网的关于授权标头的不同组合)。希望你能给我任何关于如何解决这个问题的建议。

我会很感激的。

谢谢。