c# - 从 ASP.NET 应用程序获取 Box API 的访问 token ?

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

我有我的授权码、客户端 ID、客户端密码,现在要将文件上传到我的 Box 帐户,我需要拥有访问 token 。我正在使用复制到 stackoverflow 中某处的以下代码来获取访问 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 获取访问 token 吗?

最佳答案

下面的代码完成了这项工作:

        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"]);
        }

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

关于c# - 从 ASP.NET 应用程序获取 Box API 的访问 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40826251/

相关文章:

c# - 可以在 NHibernate 中将 1 个表与 1 个表连接超过 1 次吗?

c# - 对列表中的月份进行排序

c# - DataGridView 选中行上下移动

c# - 匿名实例化期间对象初始值设定项中的 out 参数

c# - 如何在 asp.net 中使用日期和整数作为发票号

c# - FullCalendar 事件添加和更新示例

asp.net - ExecuteReader 占用时间,不是在 SQL Server 中吗?

android - 如何在 OAuth 2.0 中验证访问 token ?

facebook - 从 cookie 获取访问 token 以与 Facebook Graph API 一起使用

Facebook。 fatal error : Uncaught OAuthException: An active access token must be used to query information about the current user