65.9K
CodeProject 正在变化。 阅读更多。
Home

基于 RestSharp 的用于 Box.com 云服务的简单单页控制台应用程序

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2013年4月8日

LGPL3

3分钟阅读

viewsIcon

29179

downloadIcon

626

本文描述了如何使用 RestSharp SDK 构建用于 Box.com 云服务的应用程序

本系列文章对那些打算将其桌面应用程序用于 Box.com 云服务,但犹豫不决,因为他们面临着许多可用机会,并且已经为陛下 WWW 贡献了内容,将很有用。 如果您,这篇文章的读者,就是其中之一,那么简单易用的“复制和粘贴”代码正在等着您! :)

本文继续了以 DropBox 解释开始的简短入门系列。

背景

如今,云服务是每个人都想使用的东西。 似乎加入流行的云集团非常简单快捷。 特定云服务提供商的文档页面通常包含大量信息,并且由于云的分布式特性,经常指定自定义 REST 风格的 API。 这种规范足以理解服务提供商提供的许多特性,但并没有使我们更接近于使用任何常规开发工具和现代编程语言的实际实现。

RestSharp SDK 提供了许多已经实现的功能,例如 OAuth v1 和 OAuth v2 协议,REST 协议,还有更多,甚至为我们提供了一种以原生方式使用 RestSharp SDK 的 框架

在使用和学习应用程序之前,请确保您已经完成了以下步骤: 注册到 Box.com 并创建一个 Box.com 应用程序(即,获取 App key/App secret 对)。 您可以在 Box.com 开发资源 这里阅读解释这些简单步骤的说明。

Using the Code

本文为您提供了完整的 MS Visual Studio 2010 Express 应用程序,该应用程序能够获取 OAuth v2 访问代码、用户批准、访问令牌,并检索用户的帐户信息,作为 Box.com 服务使用的一个常规示例。

让我们逐步了解应用程序中最有趣的部分。

配置应用程序

将您获得的 App key/App secret 对放入下面的常量字符串中。 这是一个重要的步骤,也是唯一需要您贡献以使其真实有效的一段代码

private const string mc_apiKey = "YOUR_API_KEY";
private const string mc_appsecret = "YOUR_APP_SECRET";

获取访问代码并从用户那里获得访问授权

此步骤对应于 授权 操作

                //
                // Get Authorization Code and an Approval from the User
                //

                var baseUrl = "https://www.box.com";

                var client = new RestClient(baseUrl);

                // Create a Callback URL
                string sAuthorizationCallBackURL = string.Format(
                    sLoopbackCallback,
                    auth_GetRandomUnusedPort(), Assembly.GetEntryAssembly().GetName().Name
                    );

                var request = new RestRequest(
                    string.Format(
                    "/api/oauth2/authorize?response_type=code&client_id={0}&state=authenticated&redirect_uri={1}",
                    mc_apiKey, sAuthorizationCallBackURL
                    ), Method.POST);

                bool bHasUserGrantedAccess = false;

                var url = client.BuildUri(request).ToString();

                // Set up a local HTTP server to accept authetization callback

                string auth_code = null;
                var resetEvent = new ManualResetEvent(false);
                using (var svr = SimpleServer.Create(sAuthorizationCallBackURL, context =>
                {
                    var qs = HttpUtility.ParseQueryString(context.Request.RawUrl);
                    auth_code = qs["code"];

                    if (!string.IsNullOrEmpty(auth_code))
                    {
                        // The user has granted access
                        bHasUserGrantedAccess = true;
                    }

                    // Resume execution...
                    resetEvent.Set();

                }))
                {
                    // Launch a default browser to get the user's approval
                    System.Diagnostics.Process.Start(url);

                    // Wait until the user decides whether to grant access
                    resetEvent.WaitOne();

                }

                if (false == bHasUserGrantedAccess)
                {
                    // The user has not granded access
                    break;
                }

                string authorizationCode = auth_code;

获取访问令牌

此步骤对应于 令牌 操作

                //
                // Get Access Token
                //

                request = new RestRequest("/api/oauth2/token", Method.POST);

                request.AddParameter("grant_type", "authorization_code");
                request.AddParameter("code", authorizationCode);
                request.AddParameter("client_id", mc_apiKey);
                request.AddParameter("client_secret", mc_appsecret);

                var response = client.Execute(request);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    break;
                }


                // Extract the Access Token

                // output parameter:
                accessToken = response.Data;


                if (string.IsNullOrEmpty(accessToken.access_token) ||
                    string.IsNullOrEmpty(accessToken.refresh_token) ||
                    (0 == accessToken.expires_in))
                {
                    break;
                }

刷新访问令牌(目前此过程应每小时重复一次,尽管实际服务使用时间如何)

此步骤对应于 令牌 操作

                //
                // Refresh the access token (should be done if the 1 hour passed since the last access token has been obtained)
                //
                // Please not, the step refresh would fail in case the 1 hour has not passed
                // That is why the code has been cut using the preprocessor
                //

#if USE_REFRESH_TOKEN
                request = new RestRequest("/api/oauth2/token", Method.POST);

                request.AddParameter("grant_type", "refresh_token");
                request.AddParameter("code", accessToken.access_token);
                request.AddParameter("client_id", mc_apiKey);
                request.AddParameter("client_secret", mc_appsecret);
                request.AddParameter("refresh_token", accessToken.refresh_token);

                response = client.Execute(request);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    break;
                }


                // Extract the Access Token

                // output parameter:
                accessToken = response.Data;


                if (string.IsNullOrEmpty(accessToken.access_token) ||
                    string.IsNullOrEmpty(accessToken.refresh_token) ||
                    (0 == accessToken.expires_in))
                {
                    break;
                }

#endif // USE_REFRESH_TOKEN

获取用户帐户信息

此步骤对应于 获取当前用户的信息 操作

                //
                // Below is a sample how to access any Box service regular using the valid access token
                //

                baseUrl = "https://api.box.com";

                client = new RestClient(baseUrl);

                request = new RestRequest(string.Format("/{0}/users/me", mc_version), Method.GET);

                request.AddParameter(
                    "Authorization",
                    string.Format("Bearer {0}", accessToken.access_token), ParameterType.HttpHeader);

                var responseAccountInfo = client.Execute(request);

                if (responseAccountInfo.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    break;
                }

                AccountInfo accountInfo = responseAccountInfo.Data;

                Console.WriteLine("Got access to the \"{0}\" account with ID=\"{1}\" and \"{2}\" e-mail. ",
                    accountInfo.name,
                    accountInfo.id,
                    accountInfo.login);

关注点

本文的主要目标是为 C# 开发人员配备一个完整的参考应用程序,以加快了解其工作原理、从何处开始以及如何使其运行的过程 :)

让我对其他正在寻找此类帮助的开发人员做出小而谦逊的贡献。

谢谢

我想对构成本文背景的贡献说一些好话

历史

2013-04-05 初始修订

© . All rights reserved.