HttpClient和设置授权标头 [英] HttpClient and setting Authorization headers

查看:358
本文介绍了HttpClient和设置授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向 Basecamp API 进行简单的请求,按照提供的说明添加示例用户代理和我的凭据后,我一直收到403 Forbidden响应.

I'm trying to make a simple request to the Basecamp API, I'm following the instructions provided adding in a sample user agent and my credentials yet I keep getting a 403 Forbidden response back.

我的凭据绝对正确,是否是我的请求/凭据设置不正确的情况?

My credentials are definitely correct so is it a case of my request/credentials being set incorrectly?

这就是我所拥有的(已删除的个人信息):

This is what I have (removed personal info):

var httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("User-Agent", "MyApp [EMAIL ADDRESS]") });

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
            Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]"))));

var response = await httpClient.PostAsync("https://basecamp.com/[USER ID]/api/v1/projects.json", content);
var responseContent = response.Content;

using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
     Console.WriteLine(await reader.ReadToEndAsync());
}

推荐答案

快速浏览他们的文档似乎表明projects.json 端点在POST正文中接受以下内容:

A quick look over their documentation seems to indicate that the projects.json endpoint accepts the following in the body of the POST:

{
    "name": "This is my new project!",
    "description": "It's going to run real smooth"
}

您正在发送User-Agent作为POST正文.我建议您按以下方式更改代码:

You're sending the User-Agent as the POST body. I'd suggest you change your code as follows:

    var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]")));
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp [EMAIL ADDRESS]");
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
        var response = await httpClient.PostAsJsonAsync(
            "https://basecamp.com/[USER ID]/api/v1/projects.json",
            new {
                name = "My Project",
                description = "My Project Description"
            });

        var responseContent = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseContent);
    }

这会按照文档中的说明发布有效负载,并在标题中按原样设置您的用户代理.

This posts the payload as specified in the docs and sets your user agent in the headers as it should be.

这篇关于HttpClient和设置授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆