1

我正在开发一个需要使用 Clockify API 的新应用程序。当我为概念验证制作测试应用程序时,我注意到我收到 401 错误,这是对使用其基本功能之一的响应,即按工作空间获取客户。我是否缺少身份验证的内容?我需要在我的个人资料上允许设置吗?我得到的错误是:System.Net.WebException:'远程服务器返回错误:(401)未经授权。' 谢谢。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Api
{
    public class ApiHelper
    {
        public static HttpClient ApiClient { get; set; } = new HttpClient();

        public static void InitializeClient(string username, string password)
        {
            ApiClient = new HttpClient();
            ApiClient.BaseAddress = new Uri("https://api.clockify.me/api/");
            ApiClient.DefaultRequestHeaders.Accept.Clear();
            ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        public static void GetClientsFromWorkspace(string workspace)
        {
            ApiClient.DefaultRequestHeaders.Add("X-Api-Key", "*********");
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.clockify.me/api/workspaces/" + workspace + "/clients");
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "GET";
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        }
    }
}
4

1 回答 1

1

您正在设置 api 密钥标头,ApiClient但随后使用新创建HttpWebRequest的没有所需的 api 密钥标头提出请求。

您应该使用 提出请求ApiClient或将X-Api-Key标头添加到HttpWebRequest如下:

httpWebRequest.Headers.Add(“X-Api-Key”, “********”)
于 2019-04-11T21:50:33.680 回答