C# 非常奇怪的错误?
我收到了一个我没有预料到的401错误。我100%确信密码和用户名是正确的。当我在邮递员身上试用它时,它起作用了,我得到了我期望的数据。但是在这段代码中,.downloadstring方法返回一个401错误。我创建了一个新的harvest帐户,并尝试使用相同的代码访问该帐户,只需更改密码和用户名,即可获得所需的API数据。是否有其他原因导致错误密码或用户名错误401被缓存C# 非常奇怪的错误?,c#,api,http-status-code-401,C#,Api,Http Status Code 401,我收到了一个我没有预料到的401错误。我100%确信密码和用户名是正确的。当我在邮递员身上试用它时,它起作用了,我得到了我期望的数据。但是在这段代码中,.downloadstring方法返回一个401错误。我创建了一个新的harvest帐户,并尝试使用相同的代码访问该帐户,只需更改密码和用户名,即可获得所需的API数据。是否有其他原因导致错误密码或用户名错误401被缓存 public List<Project> GetAllProjects() { uri = "https:
public List<Project> GetAllProjects()
{
uri = "https://bruh.harvestapp.com/projects";
jsonPath = Path.Combine(HostingEnvironment.MapPath("~/App_Data"), "projects.json");
using (WebClient webClient = new WebClient())
{
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
webClient.Headers[HttpRequestHeader.Accept] = "application/json";
webClient.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword));
string response = webClient.DownloadString(uri);
projectsList = JsonConvert.DeserializeObject<List<Wrapper>>(response).Select(p => p.project).ToList();
}
return projectsList;
}
根据harvest的C代码示例,有几件事需要更改:
static void Main(string[] args)
{
HttpWebRequest request;
HttpWebResponse response = null;
StreamReader reader;
StringBuilder sbSource;
// 1. Set some variables specific to your account.
string uri = "https://yoursubdomain.harvestapp.com/projects";
string username="youremail@somewhere.com";
string password="yourharvestpassword";
string usernamePassword = username + ":" + password;
ServicePointManager.ServerCertificateValidationCallback = Validator;
try
{
request = WebRequest.Create(uri) as HttpWebRequest;
request.MaximumAutomaticRedirections = 1;
request.AllowAutoRedirect = true;
// 2. It's important that both the Accept and ContentType headers are
// set in order for this to be interpreted as an API request.
request.Accept = "application/xml";
request.ContentType = "application/xml";
request.UserAgent = "harvest_api_sample.cs";
// 3. Add the Basic Authentication header with username/password string.
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
using (response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse == true && response != null)
{
reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
sbSource = new StringBuilder(reader.ReadToEnd());
// 4. Print out the XML of all projects for this account.
Console.WriteLine(sbSource.ToString());
}
}
}
我在用你在《邮递员》上说的那个词。让我怀疑这一点。您是否使用Fiddler检查请求是否100%相同?我认为真正的问题在于请求头。您在授权方面有问题。您是否检查了HARVEST-API接受标头的格式。或者你是否发送了正确的令牌,即。用户名:密码或者如果你使用的是基本身份验证,它说用户名+:+密码应该在标题中发送。我让它工作了。问题是密码中包含一个§符号,c在读取时有问题。。。无论如何,谢谢你抽出时间