【问题标题】:Get an access token from box API from asp.net application?从 asp.net 应用程序的框 API 获取访问令牌?
【发布时间】:2017-04-11 02:38:08
【问题描述】:

我有我的身份验证码、客户 ID、客户密码,现在要将文件上传到我的 Box 帐户,我需要有 ACCESS TOKEN。我正在使用在 stackoverflow 中复制的以下代码来获取 ACCESS TOKEN。

public string GetAccessToken(string code, string ClientId, string ClientSecret)
    {
        RestClient rs = new RestClient();
        string grant_type = "authorization_code";
        RestRequest request = new RestRequest(Method.POST);
        IRestRequest reuest = request;
        string strHeaders = null;
        RestResponse response = default(RestResponse);
        IRestResponse resp = response;
        string strResponse = null;

        try
        {
            rs.BaseUrl = "https://www.box.com/api/oauth2/token";
            request.Resource = "oauth2/token";
            strHeaders = string.Format("grant_type={0}&code={1}&client_id={2}&client_secret={3}", grant_type, code, ClientId, ClientSecret);
            request.AddHeader("Authorization", strHeaders);
            resp = rs.Execute(reuest);
            strResponse = resp.Content;

            return strResponse;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

响应的内容类型是 HTML,而不是他们在文档页面中提到的 JSON。请您帮助我如何使用 asp.net 应用程序从 BOX API 获取访问令牌?

【问题讨论】:

  • 你会得到什么 html 响应。看一下,因为它可能是一条错误消息。收到成功的响应码了吗?
  • 是的。收到成功的响应码。

标签: c# asp.net access-token restsharp box


【解决方案1】:

下面的代码完成了工作:

        public string GetAccessToken()
        {
        string param = string.Format("grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}", CODE, CLIENT_ID, CLIENT_SECRET);

        var client = new RestClient("https://api.box.com/oauth2/token/");
        var request = new RestRequest(Method.POST);
        request.AddHeader("content-type", "application/x-www-form-urlencoded");
        request.AddParameter("application/x-www-form-urlencoded", param, ParameterType.RequestBody);
        var response = client.Execute(request);
        var json = JObject.Parse(response.Content);

        return Convert.ToString(json["access_token"]);
        }

请注意我在代码中添加的标头和参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 2013-08-05
    • 2013-06-09
    • 2011-12-29
    相关资源
    最近更新 更多