109 | {
110 | {"status" , string.Format("发布自SinaWeiboSDK_V3@{0:HH:mm:ss}", DateTime.Now)}
111 | });
112 |
113 | console.attention("{0}", result);
114 | if (result.IsSuccessStatusCode)
115 | {
116 |
117 | console.data(result.Content.ReadAsStringAsync().Result);
118 | console.info("发布成功!");
119 | }
120 | }
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/ConsoleDemo/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ConsoleDemo/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/LICENSE
--------------------------------------------------------------------------------
/MvcDemo/App_Start/FilterConfig.cs:
--------------------------------------------------------------------------------
1 | using System.Web;
2 | using System.Web.Mvc;
3 |
4 | namespace MvcDemo
5 | {
6 | public class FilterConfig
7 | {
8 | public static void RegisterGlobalFilters(GlobalFilterCollection filters)
9 | {
10 | filters.Add(new HandleErrorAttribute());
11 | }
12 | }
13 | }
--------------------------------------------------------------------------------
/MvcDemo/App_Start/RouteConfig.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Web;
5 | using System.Web.Mvc;
6 | using System.Web.Routing;
7 |
8 | namespace MvcDemo
9 | {
10 | public class RouteConfig
11 | {
12 | public static void RegisterRoutes(RouteCollection routes)
13 | {
14 | routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
15 |
16 | routes.MapRoute(
17 | name: "Default",
18 | url: "{controller}/{action}/{id}",
19 | defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
20 | );
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/MvcDemo/Content/site.css:
--------------------------------------------------------------------------------
1 | footer
2 | {
3 | background-color:#4400D9;
4 | height:80px;
5 | padding:20px 0;
6 | color:#fff;
7 | margin:30px 0 0 0;
8 | }
9 |
--------------------------------------------------------------------------------
/MvcDemo/Controllers/DemoController.cs:
--------------------------------------------------------------------------------
1 | using NetDimension.OpenAuth.Sina;
2 | using Newtonsoft.Json;
3 | using Newtonsoft.Json.Linq;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Configuration;
7 | using System.Drawing;
8 | using System.Drawing.Imaging;
9 | using System.IO;
10 | using System.Linq;
11 | using System.Web;
12 | using System.Web.Mvc;
13 |
14 | namespace MvcDemo.Controllers
15 | {
16 | public class DemoController : Controller
17 | {
18 | //
19 | // GET: /Demo/
20 |
21 | public ActionResult Index()
22 | {
23 | return View();
24 | }
25 |
26 | ///
27 | /// 封装一个方法来初始化OpenAuth客户端
28 | ///
29 | ///
30 | private SinaWeiboClient GetOpenAuthClient()
31 | {
32 | var accessToken = Session["access_token"] == null ? string.Empty : (string)Session["access_token"];
33 | var uid = Request.Cookies["uid"] == null ? string.Empty : Request.Cookies["uid"].Value;
34 |
35 | var settings = ConfigurationManager.AppSettings;
36 | var client = new SinaWeiboClient(settings["appKey"], settings["appSecret"], settings["callbackUrl"], accessToken, uid);
37 |
38 | return client;
39 | }
40 |
41 | ///
42 | /// 授权认证
43 | ///
44 | /// 新浪返回的code
45 | ///
46 | public ActionResult Authorized(string code)
47 | {
48 | if (string.IsNullOrEmpty(code))
49 | {
50 | return RedirectToAction("Index");
51 | }
52 |
53 |
54 | var client = GetOpenAuthClient();
55 |
56 | client.GetAccessTokenByCode(code);
57 |
58 | if (client.IsAuthorized)
59 | {
60 | //用session记录access token
61 | Session["access_token"] = client.AccessToken;
62 | //用cookie记录uid
63 | Response.AppendCookie(new HttpCookie("uid", client.UID) { Expires = DateTime.Now.AddDays(7) });
64 | return RedirectToAction("Index");
65 | }
66 | else
67 | {
68 | return RedirectToAction("Index");
69 | }
70 |
71 | }
72 |
73 | ///
74 | /// 获取最新微博
75 | ///
76 | ///
77 | public ActionResult GetPublicTimeline()
78 | {
79 | var client = GetOpenAuthClient();
80 |
81 | if (!client.IsAuthorized)
82 | {
83 | return Json(new
84 | {
85 | authorized = false,
86 | });
87 | }
88 | // 调用获取当前登录用户及其所关注用户的最新微博api
89 | // 参考:http://open.weibo.com/wiki/2/statuses/friends_timeline
90 | var response = client.HttpGet("statuses/friends_timeline.json");
91 |
92 | return Content(response.Content.ReadAsStringAsync().Result, "application/json");
93 |
94 |
95 | }
96 | ///
97 | /// 获取用户信息
98 | ///
99 | ///
100 | public ActionResult GetUserState()
101 | {
102 | var client = GetOpenAuthClient();
103 |
104 | if (!client.IsAuthorized)
105 | {
106 | return Json(new
107 | {
108 | authorized = false,
109 | url = client.GetAuthorizationUrl()
110 | });
111 | }
112 |
113 | // 调用获取获取用户信息api
114 | // 参考:http://open.weibo.com/wiki/2/users/show
115 | var response = client.HttpGet("users/show.json", new
116 | {
117 | uid = client.UID
118 | });
119 |
120 | if (response.IsSuccessStatusCode)
121 | {
122 | var json = new JObject();
123 | json["authorized"] = true;
124 | json["data"] = JObject.Parse(response.Content.ReadAsStringAsync().Result);
125 | return Content(json.ToString(Formatting.None), "application/json");
126 | }
127 | else
128 | {
129 | var json = new JObject();
130 | json["authorized"] = false;
131 | json["data"] = JObject.Parse(response.Content.ReadAsStringAsync().Result);
132 |
133 | json["authorized"] = true;
134 | return Content(json.ToString(Formatting.None), "application/json");
135 | }
136 | }
137 | ///
138 | /// 发微博
139 | ///
140 | ///
141 | ///
142 | ///
143 | public ActionResult PostStatus(string status, string img)
144 | {
145 | var imgFile = new FileInfo(Server.MapPath(string.Format("~/tmp/{0}", img)));
146 |
147 | var client = GetOpenAuthClient();
148 |
149 | if (!client.IsAuthorized)
150 | {
151 | return Json(false);
152 | }
153 |
154 | if (imgFile.Exists)
155 | {
156 | // 调用发图片微博api
157 | // 参考:http://open.weibo.com/wiki/2/statuses/upload
158 | var response = client.HttpPost("statuses/upload.json", new
159 | {
160 | status = status,
161 | pic = imgFile //imgFile: 对于文件上传,这里可以直接传FileInfo对象
162 | });
163 |
164 | if (response.IsSuccessStatusCode)
165 | {
166 | return Json(true);
167 | }
168 | else
169 | {
170 | return Json(false);
171 | }
172 |
173 |
174 | }
175 | else
176 | {
177 | // 调用发微博api
178 | // 参考:http://open.weibo.com/wiki/2/statuses/update
179 | var response = client.HttpPost("statuses/update.json", new
180 | {
181 | status = status
182 | });
183 |
184 | if (response.IsSuccessStatusCode)
185 | {
186 | return Json(true);
187 | }
188 | else
189 | {
190 | return Json(false);
191 | }
192 | }
193 | }
194 |
195 |
196 | ///
197 | /// 上传图片
198 | ///
199 | ///
200 | ///
201 | public ActionResult UploadImage(HttpPostedFileBase file)
202 | {
203 |
204 | try
205 | {
206 | var img = new Bitmap(file.InputStream);
207 |
208 | var fileName = string.Format("{0:yyyyMMddHHmmss}{1}", DateTime.Now, file.FileName.Substring(file.FileName.LastIndexOf('.')));
209 |
210 | file.SaveAs(Server.MapPath(string.Format("~/tmp/{0}", fileName)));
211 |
212 | return Json(new { success = true, fileName = fileName });
213 | }
214 | catch
215 | {
216 | return Json(new { success = false });
217 | }
218 |
219 | }
220 |
221 |
222 |
223 | }
224 |
225 |
226 |
227 | }
228 |
--------------------------------------------------------------------------------
/MvcDemo/Controllers/HomeController.cs:
--------------------------------------------------------------------------------
1 | using NetDimension.OpenAuth;
2 | using NetDimension.OpenAuth.Sina;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Configuration;
6 | using System.Linq;
7 | using System.Web;
8 | using System.Web.Mvc;
9 |
10 | namespace MvcDemo.Controllers
11 | {
12 | public class HomeController : Controller
13 | {
14 | //
15 | // GET: /Home/
16 |
17 | public ActionResult Index()
18 | {
19 |
20 |
21 | return View();
22 | }
23 |
24 |
25 | public ActionResult GetAuthorizationState()
26 | {
27 | var settings = ConfigurationManager.AppSettings;
28 |
29 | var oauth = new SinaWeiboClient(settings["appKey"], settings["appSecret"], settings["callbackUrl"]);
30 |
31 |
32 | if (Request.Cookies["access_token"] == null || string.IsNullOrEmpty(Request.Cookies["access_token"].Value))
33 | {
34 | return Json(new
35 | {
36 | authorized = false
37 | }, JsonRequestBehavior.AllowGet);
38 | }
39 |
40 |
41 |
42 | var accessToken = Request.Cookies["access_token"].Value;
43 | var uid = Request.Cookies["uid"].Value;
44 |
45 | oauth.AccessToken = accessToken;
46 | oauth.UID = uid;
47 |
48 | //较v2版的sdk,新的v3版sdk移除了所有的本地化api接口,因为新浪的接口变来变去,踩着滑板鞋也追不着他们魔鬼的步伐。
49 | //因此v3版的调用方式改为直接填写官方api名称和传递官方文档中要求的参数的方式来调用,返回结果需要自行使用json接卸器解析。
50 | var response = oauth.HttpGet("user/show.json", new
51 | {
52 | uid = uid
53 | });
54 |
55 |
56 | return Json(response.Content.ReadAsStringAsync().Result, JsonRequestBehavior.AllowGet);
57 |
58 | }
59 |
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/MvcDemo/Global.asax:
--------------------------------------------------------------------------------
1 | <%@ Application Codebehind="Global.asax.cs" Inherits="MvcDemo.MvcApplication" Language="C#" %>
2 |
--------------------------------------------------------------------------------
/MvcDemo/Global.asax.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Web;
5 | using System.Web.Http;
6 | using System.Web.Mvc;
7 | using System.Web.Routing;
8 |
9 | namespace MvcDemo
10 | {
11 | // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,
12 | // 请访问 http://go.microsoft.com/?LinkId=9394801
13 | public class MvcApplication : System.Web.HttpApplication
14 | {
15 | protected void Application_Start()
16 | {
17 | AreaRegistration.RegisterAllAreas();
18 |
19 | FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
20 | RouteConfig.RegisterRoutes(RouteTable.Routes);
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/MvcDemo/Icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/Icon.png
--------------------------------------------------------------------------------
/MvcDemo/MvcDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 |
8 |
9 | 2.0
10 | {C4F823E1-D35F-4B93-9AB8-B2D9D64C15FD}
11 | {E3E379DF-F4C6-4180-9B81-6769533ABE47};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}
12 | Library
13 | Properties
14 | MvcDemo
15 | MvcDemo
16 | v4.0
17 | false
18 | true
19 |
20 |
21 |
22 |
23 | SAK
24 | SAK
25 | SAK
26 | SAK
27 | ..\
28 | true
29 |
30 |
31 |
32 | true
33 | full
34 | false
35 | bin\
36 | DEBUG;TRACE
37 | prompt
38 | 4
39 |
40 |
41 | pdbonly
42 | true
43 | bin\
44 | TRACE
45 | prompt
46 | 4
47 |
48 |
49 |
50 |
51 | False
52 | ..\packages\Newtonsoft.Json.6.0.8\lib\net40\Newtonsoft.Json.dll
53 |
54 |
55 |
56 |
57 |
58 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.IO.dll
59 |
60 |
61 | False
62 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.dll
63 |
64 |
65 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.Extensions.dll
66 |
67 |
68 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.Primitives.dll
69 |
70 |
71 | False
72 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.WebRequest.dll
73 |
74 |
75 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Runtime.dll
76 |
77 |
78 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Threading.Tasks.dll
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 | True
88 | ..\packages\Microsoft.AspNet.Mvc.4.0.40804.0\lib\net40\System.Web.Mvc.dll
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 | True
101 | ..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll
102 |
103 |
104 | True
105 | ..\packages\Microsoft.AspNet.Mvc.FixedDisplayModes.1.0.0\lib\net40\Microsoft.Web.Mvc.FixedDisplayModes.dll
106 |
107 |
108 | ..\packages\Microsoft.AspNet.WebApi.Client.4.0.30506.0\lib\net40\System.Net.Http.Formatting.dll
109 |
110 |
111 | True
112 | ..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.Helpers.dll
113 |
114 |
115 | ..\packages\Microsoft.AspNet.WebApi.Core.4.0.30506.0\lib\net40\System.Web.Http.dll
116 |
117 |
118 | True
119 | ..\packages\Microsoft.AspNet.Razor.2.0.30506.0\lib\net40\System.Web.Razor.dll
120 |
121 |
122 | True
123 | ..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.WebPages.dll
124 |
125 |
126 | True
127 | ..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.WebPages.Deployment.dll
128 |
129 |
130 | True
131 | ..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.WebPages.Razor.dll
132 |
133 |
134 |
135 |
136 |
137 |
138 | Global.asax
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 | Designer
180 |
181 |
182 | Web.config
183 |
184 |
185 | Web.config
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 | {76fc909d-bda2-4fce-9b9f-b503a13df44f}
204 | NetDimension.OpenAuth.Sina
205 |
206 |
207 | {38b68338-7fc0-4ab7-b8a7-674e0bcbf899}
208 | NetDimension.OpenAuth
209 |
210 |
211 |
212 | 10.0
213 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 | True
226 | True
227 | 4801
228 | /
229 | http://localhost:4801/
230 | False
231 | False
232 |
233 |
234 | False
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 | 这台计算机上缺少此项目引用的 NuGet 程序包。启用“NuGet 程序包还原”可下载这些程序包。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
257 |
--------------------------------------------------------------------------------
/MvcDemo/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过下列特性集
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("MvcDemo")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Net Dimension Studio")]
12 | [assembly: AssemblyProduct("MvcDemo")]
13 | [assembly: AssemblyCopyright("版权所有(C) Net Dimension Studio 2015")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 会使此程序集中的类型
18 | // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的某个类型,
19 | // 请针对该类型将 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("6efb0fce-df94-4fc6-a4fb-9dd4a4cca9f6")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 内部版本号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“修订号”和“内部版本号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
36 |
--------------------------------------------------------------------------------
/MvcDemo/Scripts/_references.js:
--------------------------------------------------------------------------------
1 | ///
2 | ///
3 |
--------------------------------------------------------------------------------
/MvcDemo/Scripts/jquery.upload.js:
--------------------------------------------------------------------------------
1 | /**
2 | * jQuery upload v1.2
3 | * http://www.ponxu.com
4 | *
5 | * @author xwz
6 | */
7 | (function($) {
8 | var noop = function(){ return true; };
9 | var frameCount = 0;
10 |
11 | $.uploadDefault = {
12 | url: '',
13 | fileName: 'filedata',
14 | dataType: 'json',
15 | params: {},
16 | onSend: noop,
17 | onSubmit: noop,
18 | onComplate: noop
19 | };
20 |
21 | $.upload = function(options) {
22 | var opts = $.extend(jQuery.uploadDefault, options);
23 | if (opts.url == '') {
24 | return;
25 | }
26 |
27 | var canSend = opts.onSend();
28 | if (!canSend) {
29 | return;
30 | }
31 |
32 | var frameName = 'upload_frame_' + (frameCount++);
33 | var iframe = $('').attr('name', frameName);
34 | var form = $('').attr('name', 'form_' + frameName);
35 | form.attr("target", frameName).attr('action', opts.url);
36 |
37 | // form中增加数据域
38 | var formHtml = '';
39 | for (key in opts.params) {
40 | formHtml += '';
41 | }
42 | form.append(formHtml);
43 |
44 | iframe.appendTo("body");
45 | form.appendTo("body");
46 |
47 | form.submit(opts.onSubmit);
48 |
49 | // iframe 在提交完成之后
50 | iframe.load(function() {
51 | var contents = $(this).contents().get(0);
52 | var data = $(contents).find('body').text();
53 | if ('json' == opts.dataType) {
54 | data = window.eval('(' + data + ')');
55 | }
56 | opts.onComplate(data);
57 | setTimeout(function() {
58 | iframe.remove();
59 | form.remove();
60 | }, 5000);
61 | });
62 |
63 | // 文件框
64 | var fileInput = $('input[type=file][name=' + opts.fileName + ']', form);
65 | fileInput.click();
66 | };
67 | })(jQuery);
68 |
69 | // 选中文件, 提交表单(开始上传)
70 | var onChooseFile = function(fileInputDOM) {
71 | var form = $(fileInputDOM).parent();
72 | form.submit();
73 | };
74 |
--------------------------------------------------------------------------------
/MvcDemo/Scripts/npm.js:
--------------------------------------------------------------------------------
1 | // This file is autogenerated via the `commonjs` Grunt task. You can require() this file in a CommonJS environment.
2 | require('../../js/transition.js')
3 | require('../../js/alert.js')
4 | require('../../js/button.js')
5 | require('../../js/carousel.js')
6 | require('../../js/collapse.js')
7 | require('../../js/dropdown.js')
8 | require('../../js/modal.js')
9 | require('../../js/tooltip.js')
10 | require('../../js/popover.js')
11 | require('../../js/scrollspy.js')
12 | require('../../js/tab.js')
13 | require('../../js/affix.js')
--------------------------------------------------------------------------------
/MvcDemo/Views/Demo/Index.cshtml:
--------------------------------------------------------------------------------
1 | @{
2 | ViewBag.Title = "Weibo SDK Web Demo";
3 | }
4 |
5 | @section scripts
6 | {
7 |
8 |
15 |
16 |
31 |
32 |
43 |
44 |
191 | }
192 |
193 |
194 |
195 |
196 | 今天想说点什么?
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
210 |
211 |
212 |
213 | 最新微博
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 | 登录状态
225 |
226 |
227 |
228 |
--------------------------------------------------------------------------------
/MvcDemo/Views/Home/Index.cshtml:
--------------------------------------------------------------------------------
1 | @{
2 | ViewBag.Title = "欢迎";
3 | }
4 |
5 |
6 |

7 |

8 |
9 |
10 |
11 | 欢迎使用WeiboSDK_v3版
12 |
13 |
14 | 项目地址:http://weibosdk.codeplex.com
15 |
16 |
17 |
18 | GitHub:https://github.com/NetDimension/WeiboSDK
19 |
20 |
21 |
22 | 第一步
23 | 根据自己的需求修改Web.config中的appKey、appSecret和callbackUrl字段。
24 | 本示例用的callbackUrl为“http://127.0.0.1:4801/Demo/Authorized”,所以如果要顺利运行本示例请讲在新浪微博开放平台中的回调地址也设置成这个。
25 |
26 |
27 |
28 | 第二步
29 | 如果使用IIS Express调试,请自行修改IIS Express的applicationhost.config文件,确保127.0.0.1:<端口>能够访问(因为新浪后台的回调地址可以使用IP地址,但不能使用localhost)。
30 | applicationhost.config文件在“文档\IISExpress\config”文件夹中。
31 | 找到下列配置项,并添加“<binding protocol="http" bindinginformation="*:4801:127.0.0.1" />”:
32 |
44 | 另外,如果访问http://127.0.0.1:4801返回Bad Request错误的话,请用管理员权限运行你的VS.
45 | 第三步
46 |
47 | 点这里开始运行Demo
48 |
49 | 如果授权成功,程序会将获取到的access token及当前登录用户的uid暂存到cookie中。
50 |
51 |
--------------------------------------------------------------------------------
/MvcDemo/Views/Shared/_Layout.cshtml:
--------------------------------------------------------------------------------
1 | @{
2 | Layout = null;
3 | }
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | @ViewBag.Title - WeiboSDK Web Demo
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
32 |
33 | @RenderBody()
34 |
35 |
36 |
42 |
43 | @RenderSection("scripts", false)
44 |
45 |
46 |
--------------------------------------------------------------------------------
/MvcDemo/Views/Web.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
39 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/MvcDemo/Views/_viewstart.cshtml:
--------------------------------------------------------------------------------
1 | @{
2 | Layout = "~/Views/Shared/_Layout.cshtml";
3 | }
4 |
5 |
--------------------------------------------------------------------------------
/MvcDemo/Web.Debug.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
17 |
18 |
29 |
30 |
--------------------------------------------------------------------------------
/MvcDemo/Web.Release.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
17 |
18 |
19 |
30 |
31 |
--------------------------------------------------------------------------------
/MvcDemo/Web.config:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/MvcDemo/fonts/FontAwesome.otf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/fonts/FontAwesome.otf
--------------------------------------------------------------------------------
/MvcDemo/fonts/fontawesome-webfont.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/fonts/fontawesome-webfont.eot
--------------------------------------------------------------------------------
/MvcDemo/fonts/fontawesome-webfont.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/fonts/fontawesome-webfont.ttf
--------------------------------------------------------------------------------
/MvcDemo/fonts/fontawesome-webfont.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/fonts/fontawesome-webfont.woff
--------------------------------------------------------------------------------
/MvcDemo/fonts/fontawesome-webfont.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/fonts/fontawesome-webfont.woff2
--------------------------------------------------------------------------------
/MvcDemo/fonts/glyphicons-halflings-regular.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/fonts/glyphicons-halflings-regular.eot
--------------------------------------------------------------------------------
/MvcDemo/fonts/glyphicons-halflings-regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/fonts/glyphicons-halflings-regular.ttf
--------------------------------------------------------------------------------
/MvcDemo/fonts/glyphicons-halflings-regular.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/fonts/glyphicons-halflings-regular.woff
--------------------------------------------------------------------------------
/MvcDemo/fonts/glyphicons-halflings-regular.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/fonts/glyphicons-halflings-regular.woff2
--------------------------------------------------------------------------------
/MvcDemo/images/Logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/images/Logo.png
--------------------------------------------------------------------------------
/MvcDemo/images/qrcode.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/images/qrcode.jpg
--------------------------------------------------------------------------------
/MvcDemo/images/step1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/MvcDemo/images/step1.png
--------------------------------------------------------------------------------
/MvcDemo/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Sina/NetDimension.OpenAuth.Sina.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {76FC909D-BDA2-4FCE-9B9F-B503A13DF44F}
8 | Library
9 | Properties
10 | NetDimension.OpenAuth.Sina
11 | NetDimension.OpenAuth.Sina
12 | v4.0
13 | 512
14 | SAK
15 | SAK
16 | SAK
17 | SAK
18 | ..\
19 | true
20 |
21 |
22 | true
23 | full
24 | false
25 | bin\Debug\
26 | DEBUG;TRACE
27 | prompt
28 | 4
29 |
30 |
31 | pdbonly
32 | true
33 | bin\Release\
34 | TRACE
35 | prompt
36 | 4
37 |
38 |
39 |
40 | False
41 | ..\packages\Newtonsoft.Json.6.0.8\lib\net40\Newtonsoft.Json.dll
42 |
43 |
44 |
45 |
46 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.IO.dll
47 |
48 |
49 | False
50 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.dll
51 |
52 |
53 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.Extensions.dll
54 |
55 |
56 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.Primitives.dll
57 |
58 |
59 | False
60 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.WebRequest.dll
61 |
62 |
63 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Runtime.dll
64 |
65 |
66 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Threading.Tasks.dll
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 | {38b68338-7fc0-4ab7-b8a7-674e0bcbf899}
85 | NetDimension.OpenAuth
86 |
87 |
88 |
89 |
90 |
91 |
92 | 这台计算机上缺少此项目引用的 NuGet 程序包。启用“NuGet 程序包还原”可下载这些程序包。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
108 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Sina/NetDimension.OpenAuth.Sina.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $id$
5 | $version$
6 | $title$
7 | $author$
8 | $author$
9 | http://LICENSE_URL_HERE_OR_DELETE_THIS_LINE
10 | http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE
11 | http://ICON_URL_HERE_OR_DELETE_THIS_LINE
12 | false
13 | $description$
14 | Summary of changes made in this release of the package.
15 | Copyright 2016
16 | Tag1 Tag2
17 |
18 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Sina/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("NetDimension.OpenAuth.Sina")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Net Dimension Studio")]
12 | [assembly: AssemblyProduct("NetDimension.OpenAuth.Sina")]
13 | [assembly: AssemblyCopyright("Copyright © Net Dimension Studio 2015")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("78b21176-53ca-422c-ac08-00c283fcba92")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Sina/SinaWeiboClient.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json.Linq;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Net.Http;
6 | using System.Text;
7 | using System.Threading.Tasks;
8 |
9 | namespace NetDimension.OpenAuth.Sina
10 | {
11 | public class SinaWeiboClient : OpenAuthenticationClientBase
12 | {
13 | const string AUTH_URL = "https://api.weibo.com/oauth2/authorize";
14 | const string TOKEN_URL = "https://api.weibo.com/oauth2/access_token";
15 | const string API_URL = "https://api.weibo.com/2/";
16 |
17 | public string UID
18 | {
19 | get;
20 | set;
21 | }
22 |
23 | public SinaWeiboClient(string appKey, string appSecret, string callbackUrl, string accessToken = null, string uid = null)
24 | : base(appKey, appSecret, callbackUrl, accessToken)
25 | {
26 | ClientName = "SinaWeibo";
27 | UID = uid;
28 |
29 | if (!(string.IsNullOrEmpty(accessToken) && string.IsNullOrEmpty(uid)))
30 | {
31 | isAccessTokenSet = true;
32 | }
33 | }
34 |
35 | protected override string AuthorizationCodeUrl
36 | {
37 | get { return AUTH_URL; }
38 | }
39 |
40 | protected override string AccessTokenUrl
41 | {
42 | get { return TOKEN_URL; }
43 | }
44 |
45 | protected override string BaseApiUrl
46 | {
47 | get { return API_URL; }
48 | }
49 |
50 | public override string GetAuthorizationUrl()
51 | {
52 | var ub = new UriBuilder(AuthorizationCodeUrl);
53 | ub.Query = string.Format("client_id={0}&response_type=code&redirect_uri={1}", ClientId, Uri.EscapeDataString(CallbackUrl));
54 |
55 |
56 |
57 | return ub.ToString();
58 | }
59 |
60 |
61 |
62 | public override void GetAccessTokenByCode(string code)
63 | {
64 |
65 |
66 | var response = HttpPost(TOKEN_URL, new
67 | {
68 | client_id = ClientId,
69 | client_secret = ClientSecret,
70 | grant_type = "authorization_code",
71 | code = code,
72 | redirect_uri = CallbackUrl
73 | });
74 |
75 | if (response.StatusCode != System.Net.HttpStatusCode.OK)
76 | return;
77 |
78 | var result = JObject.Parse(response.Content.ReadAsStringAsync().Result);
79 | if (result["access_token"] == null)
80 | {
81 | return;
82 | }
83 | AccessToken = result.Value("access_token");
84 | UID = result.Value("uid");
85 |
86 | isAccessTokenSet = true;
87 | }
88 |
89 | public override Task HttpGetAsync(string api, Dictionary parameters)
90 | {
91 | if (IsAuthorized)
92 | {
93 | if (parameters == null)
94 | parameters = new Dictionary();
95 |
96 | if (!parameters.ContainsKey("source"))
97 | {
98 | parameters["source"] = ClientId;
99 | }
100 |
101 | if (!parameters.ContainsKey("access_token"))
102 | {
103 | parameters["access_token"] = AccessToken;
104 | }
105 | }
106 |
107 |
108 |
109 | return base.HttpGetAsync(api, parameters);
110 | }
111 |
112 |
113 | public override Task HttpPostAsync(string api, Dictionary parameters)
114 | {
115 | if (IsAuthorized)
116 | {
117 | if (parameters == null)
118 | parameters = new Dictionary();
119 |
120 | if (!parameters.ContainsKey("source"))
121 | {
122 | parameters["source"] = ClientId;
123 | }
124 |
125 | if (!parameters.ContainsKey("access_token"))
126 | {
127 | parameters["access_token"] = AccessToken;
128 | }
129 | }
130 |
131 | return base.HttpPostAsync(api, parameters);
132 | }
133 |
134 |
135 |
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Sina/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Sina/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Tencent/NetDimension.OpenAuth.Tencent.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {DF5550C5-B4E3-4697-87B7-F6182DBFBC6F}
8 | Library
9 | Properties
10 | NetDimension.OpenAuth.Tencent
11 | NetDimension.OpenAuth.Tencent
12 | v4.0
13 | 512
14 | SAK
15 | SAK
16 | SAK
17 | SAK
18 | ..\
19 | true
20 |
21 |
22 | true
23 | full
24 | false
25 | bin\Debug\
26 | DEBUG;TRACE
27 | prompt
28 | 4
29 |
30 |
31 | pdbonly
32 | true
33 | bin\Release\
34 | TRACE
35 | prompt
36 | 4
37 |
38 |
39 |
40 | False
41 | ..\packages\Newtonsoft.Json.6.0.8\lib\net40\Newtonsoft.Json.dll
42 |
43 |
44 |
45 |
46 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.IO.dll
47 |
48 |
49 | False
50 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.dll
51 |
52 |
53 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.Extensions.dll
54 |
55 |
56 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.Primitives.dll
57 |
58 |
59 | False
60 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.WebRequest.dll
61 |
62 |
63 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Runtime.dll
64 |
65 |
66 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Threading.Tasks.dll
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 | {38b68338-7fc0-4ab7-b8a7-674e0bcbf899}
85 | NetDimension.OpenAuth
86 |
87 |
88 |
89 |
90 |
91 |
92 | 这台计算机上缺少此项目引用的 NuGet 程序包。启用“NuGet 程序包还原”可下载这些程序包。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
108 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Tencent/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("NetDimension.OpenAuth.Tencent")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Net Dimension Studio")]
12 | [assembly: AssemblyProduct("NetDimension.OpenAuth.Tencent")]
13 | [assembly: AssemblyCopyright("Copyright © Net Dimension Studio 2015")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("6c171a85-7a9e-43d6-b1b4-5e29b7f7586f")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Tencent/QQConnectClient.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json.Linq;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Net.Http;
6 | using System.Text;
7 | using System.Text.RegularExpressions;
8 | using System.Threading.Tasks;
9 |
10 | namespace NetDimension.OpenAuth.Tencent
11 | {
12 | public class QQConnectClient : OpenAuthenticationClientBase
13 | {
14 | const string AUTH_URL = "https://graph.qq.com/oauth2.0/authorize";
15 | const string TOKEN_URL = "https://graph.qq.com/oauth2.0/token";
16 | const string API_URL = "https://graph.qq.com/{0}?access_token={1}&oauth_consumer_key={2}&openid={3}";
17 | const string OPEN_API_URL = "https://graph.qq.com/oauth2.0/me";
18 |
19 |
20 | protected override string BaseApiUrl
21 | {
22 | get { return API_URL; }
23 | }
24 |
25 | protected override string AuthorizationCodeUrl
26 | {
27 | get { return AUTH_URL; }
28 | }
29 |
30 | protected override string AccessTokenUrl
31 | {
32 | get { return TOKEN_URL; }
33 | }
34 |
35 | public string OpenId
36 | {
37 | get;
38 | set;
39 | }
40 |
41 | public QQConnectClient(string clientId, string clientSecret, string callbackUrl, string accessToken = null, string openId = null) :
42 | base(clientId, clientSecret, callbackUrl, accessToken)
43 | {
44 | OpenId = openId;
45 | ClientName = "QQConnect";
46 | }
47 |
48 | public override string GetAuthorizationUrl()
49 | {
50 | var ub = new UriBuilder(AuthorizationCodeUrl);
51 |
52 | ub.Query = string.Format("response_type=code&client_id={0}&redirect_uri={1}&state=QQ&scope=get_user_info,add_t,add_pic_t", ClientId, Uri.EscapeDataString(CallbackUrl));
53 |
54 | return ub.ToString();
55 |
56 | }
57 |
58 | public override void GetAccessTokenByCode(string code)
59 | {
60 |
61 | var response = HttpPost(TOKEN_URL, new
62 | {
63 | grant_type = "authorization_code",
64 | client_id = ClientId,
65 | client_secret = ClientSecret,
66 | code = code,
67 | redirect_uri = CallbackUrl
68 | });
69 |
70 |
71 | if (response.StatusCode != System.Net.HttpStatusCode.OK)
72 | return;
73 |
74 |
75 | var result = response.Content.ReadAsStringAsync().Result;
76 |
77 | var accessToken = string.Empty;
78 |
79 | var pattern = @"access_token=(([\d|a-zA-Z]*))";
80 |
81 | if (Regex.IsMatch(result, pattern))
82 | {
83 | accessToken = Regex.Match(result, pattern).Groups[1].Value;
84 | }
85 |
86 | response = HttpGet(OPEN_API_URL, new Dictionary
87 | {
88 | {"access_token" , accessToken}
89 | });
90 |
91 | if (response.StatusCode != System.Net.HttpStatusCode.OK)
92 | return;
93 |
94 | result = response.Content.ReadAsStringAsync().Result;
95 |
96 | pattern = @"\""openid\"":\""([\d|a-zA-Z]+)\""";
97 |
98 | if (!Regex.IsMatch(result, pattern))
99 | {
100 | return;
101 | }
102 |
103 |
104 |
105 | AccessToken = accessToken;
106 | OpenId = Regex.Match(result, pattern).Groups[1].Value;
107 |
108 | isAccessTokenSet = true;
109 |
110 | }
111 |
112 | public override Task HttpGetAsync(string api, Dictionary parameters)
113 | {
114 | if (IsAuthorized)
115 | {
116 | if (parameters == null)
117 | parameters = new Dictionary();
118 |
119 | if (!parameters.ContainsKey("access_token"))
120 | {
121 | parameters["access_token"] = AccessToken;
122 | }
123 | if (!parameters.ContainsKey("oauth_consumer_key"))
124 | {
125 | parameters["oauth_consumer_key"] = ClientId;
126 | }
127 |
128 | if (!parameters.ContainsKey("openid"))
129 | {
130 | parameters["openid"] = OpenId;
131 | }
132 |
133 | }
134 |
135 |
136 |
137 | return base.HttpGetAsync(api, parameters);
138 | }
139 |
140 | public override Task HttpPostAsync(string api, Dictionary parameters)
141 | {
142 | if (IsAuthorized)
143 | {
144 | if (parameters == null)
145 | parameters = new Dictionary();
146 |
147 | if (!parameters.ContainsKey("access_token"))
148 | {
149 | parameters["access_token"] = AccessToken;
150 | }
151 | if (!parameters.ContainsKey("oauth_consumer_key"))
152 | {
153 | parameters["oauth_consumer_key"] = ClientId;
154 | }
155 |
156 | if (!parameters.ContainsKey("openid"))
157 | {
158 | parameters["openid"] = OpenId;
159 | }
160 | }
161 |
162 | return base.HttpPostAsync(api, parameters);
163 | }
164 |
165 |
166 |
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Tencent/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Tencent/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Winform/AuthenticationForm.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace NetDimension.OpenAuth.Winform
2 | {
3 | partial class AuthenticationForm
4 | {
5 | ///
6 | /// Required designer variable.
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// Clean up any resources being used.
12 | ///
13 | /// true if managed resources should be disposed; otherwise, false.
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Windows Form Designer generated code
24 |
25 | ///
26 | /// Required method for Designer support - do not modify
27 | /// the contents of this method with the code editor.
28 | ///
29 | private void InitializeComponent()
30 | {
31 | this.browser = new System.Windows.Forms.WebBrowser();
32 | this.panelMask = new System.Windows.Forms.Panel();
33 | this.label1 = new System.Windows.Forms.Label();
34 | this.panelMask.SuspendLayout();
35 | this.SuspendLayout();
36 | //
37 | // browser
38 | //
39 | this.browser.AllowWebBrowserDrop = false;
40 | this.browser.Dock = System.Windows.Forms.DockStyle.Fill;
41 | this.browser.IsWebBrowserContextMenuEnabled = false;
42 | this.browser.Location = new System.Drawing.Point(0, 0);
43 | this.browser.MinimumSize = new System.Drawing.Size(20, 20);
44 | this.browser.Name = "browser";
45 | this.browser.ScriptErrorsSuppressed = true;
46 | this.browser.ScrollBarsEnabled = false;
47 | this.browser.Size = new System.Drawing.Size(704, 461);
48 | this.browser.TabIndex = 0;
49 | this.browser.WebBrowserShortcutsEnabled = false;
50 | this.browser.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.browser_Navigated);
51 | //
52 | // panelMask
53 | //
54 | this.panelMask.BackColor = System.Drawing.Color.White;
55 | this.panelMask.Controls.Add(this.label1);
56 | this.panelMask.Dock = System.Windows.Forms.DockStyle.Fill;
57 | this.panelMask.Location = new System.Drawing.Point(0, 0);
58 | this.panelMask.Name = "panelMask";
59 | this.panelMask.Size = new System.Drawing.Size(704, 461);
60 | this.panelMask.TabIndex = 1;
61 | this.panelMask.Visible = false;
62 | //
63 | // label1
64 | //
65 | this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
66 | this.label1.ForeColor = System.Drawing.Color.DimGray;
67 | this.label1.Location = new System.Drawing.Point(0, 0);
68 | this.label1.Name = "label1";
69 | this.label1.Size = new System.Drawing.Size(704, 461);
70 | this.label1.TabIndex = 0;
71 | this.label1.Text = "正在验证...";
72 | this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
73 | //
74 | // AuthenticationForm
75 | //
76 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
77 | this.ClientSize = new System.Drawing.Size(704, 461);
78 | this.Controls.Add(this.panelMask);
79 | this.Controls.Add(this.browser);
80 | this.MaximizeBox = false;
81 | this.MinimizeBox = false;
82 | this.MinimumSize = new System.Drawing.Size(720, 500);
83 | this.Name = "AuthenticationForm";
84 | this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
85 | this.Text = "登录授权";
86 | this.Shown += new System.EventHandler(this.frmAuthentication_Shown);
87 | this.panelMask.ResumeLayout(false);
88 | this.ResumeLayout(false);
89 |
90 | }
91 |
92 | #endregion
93 |
94 | private System.Windows.Forms.WebBrowser browser;
95 | private System.Windows.Forms.Panel panelMask;
96 | private System.Windows.Forms.Label label1;
97 | }
98 | }
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Winform/AuthenticationForm.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel;
4 | using System.Data;
5 | using System.Drawing;
6 | using System.Linq;
7 | using System.Text;
8 | using System.Text.RegularExpressions;
9 | using System.Threading.Tasks;
10 | using System.Windows.Forms;
11 |
12 | namespace NetDimension.OpenAuth.Winform
13 | {
14 | public partial class AuthenticationForm : Form
15 | {
16 | OpenAuthenticationClientBase OpenAuth;
17 |
18 |
19 | public string Code
20 | {
21 | get;
22 | private set;
23 | }
24 | public AuthenticationForm(OpenAuthenticationClientBase openAuth)
25 | {
26 | InitializeComponent();
27 | OpenAuth = openAuth;
28 | }
29 |
30 | private void frmAuthentication_Shown(object sender, EventArgs e)
31 | {
32 | browser.Navigate(OpenAuth.GetAuthorizationUrl());
33 | }
34 |
35 | private void browser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
36 | {
37 |
38 | //Console.WriteLine(e.Url);
39 |
40 | var pattern = @"code=([\d|a-zA-Z]*)";
41 | if (Regex.IsMatch(e.Url.Query, pattern))
42 | {
43 | panelMask.Visible = true;
44 | panelMask.BringToFront();
45 | var code = Regex.Match(e.Url.Query, pattern).Groups[1].Value;
46 |
47 | Task.Factory.StartNew(() =>
48 | {
49 | OpenAuth.GetAccessTokenByCode(code);
50 | UpdateUI(() =>
51 | {
52 | if (OpenAuth.IsAuthorized)
53 | {
54 |
55 | Code = code;
56 | this.DialogResult = System.Windows.Forms.DialogResult.OK;
57 | this.Close();
58 |
59 | }
60 | else
61 | {
62 |
63 | this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
64 | this.Close();
65 | }
66 | });
67 | });
68 | }
69 | }
70 |
71 | private void UpdateUI(Action uiAction)
72 | {
73 | if (this.InvokeRequired)
74 | {
75 | this.Invoke(new MethodInvoker(uiAction));
76 | }
77 | else
78 | {
79 | uiAction();
80 | }
81 | }
82 |
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Winform/AuthenticationForm.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Winform/NetDimension.OpenAuth.Winform.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {0D1F893B-AF94-4E52-B972-A5D40E1DB670}
8 | Library
9 | Properties
10 | NetDimension.OpenAuth.Winform
11 | NetDimension.OpenAuth.Winform
12 | v4.0
13 | 512
14 | SAK
15 | SAK
16 | SAK
17 | SAK
18 |
19 |
20 | true
21 | full
22 | false
23 | bin\Debug\
24 | DEBUG;TRACE
25 | prompt
26 | 4
27 |
28 |
29 | pdbonly
30 | true
31 | bin\Release\
32 | TRACE
33 | prompt
34 | 4
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 | Form
50 |
51 |
52 | AuthenticationForm.cs
53 |
54 |
55 |
56 |
57 |
58 |
59 | {38b68338-7fc0-4ab7-b8a7-674e0bcbf899}
60 | NetDimension.OpenAuth
61 |
62 |
63 |
64 |
65 | AuthenticationForm.cs
66 |
67 |
68 |
69 |
70 |
71 |
72 |
79 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Winform/OpenAuthenticationClientExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Windows.Forms;
6 |
7 | namespace NetDimension.OpenAuth.Winform
8 | {
9 | public static class OpenAuthenticationClientExtensions
10 | {
11 |
12 | public static AuthenticationForm GetAuthenticationForm(this OpenAuthenticationClientBase oauth)
13 | {
14 | var openAuthForm = new AuthenticationForm(oauth);
15 |
16 | return openAuthForm;
17 | }
18 |
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Winform/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("NetDimension.OpenAuth.Winform")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Net Dimension Studio")]
12 | [assembly: AssemblyProduct("NetDimension.OpenAuth.Winform")]
13 | [assembly: AssemblyCopyright("Copyright © Net Dimension Studio 2015")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("2c89940c-5f24-4014-b016-49626838709b")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth.Winform/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth/MemoryFileContent.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace NetDimension.OpenAuth
7 | {
8 | public class MemoryFileContent
9 | {
10 | public string FileName
11 | {
12 | get;
13 | set;
14 | }
15 |
16 |
17 | public byte[] Content
18 | {
19 | get;
20 | set;
21 |
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth/NetDimension.OpenAuth.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {38B68338-7FC0-4AB7-B8A7-674E0BCBF899}
8 | Library
9 | Properties
10 | NetDimension.OpenAuth
11 | NetDimension.OpenAuth
12 | v4.0
13 | 512
14 | SAK
15 | SAK
16 | SAK
17 | SAK
18 | ..\
19 | true
20 |
21 |
22 | true
23 | full
24 | false
25 | bin\Debug\
26 | DEBUG;TRACE
27 | prompt
28 | 4
29 |
30 |
31 | pdbonly
32 | true
33 | bin\Release\
34 | TRACE
35 | prompt
36 | 4
37 |
38 |
39 |
40 | False
41 | ..\packages\Newtonsoft.Json.6.0.8\lib\net40\Newtonsoft.Json.dll
42 |
43 |
44 |
45 |
46 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.IO.dll
47 |
48 |
49 |
50 | False
51 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.dll
52 |
53 |
54 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.Extensions.dll
55 |
56 |
57 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.Primitives.dll
58 |
59 |
60 | False
61 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.WebRequest.dll
62 |
63 |
64 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Runtime.dll
65 |
66 |
67 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Threading.Tasks.dll
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 | 这台计算机上缺少此项目引用的 NuGet 程序包。启用“NuGet 程序包还原”可下载这些程序包。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
105 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth/OpenAuthenticationClientBase.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Net;
5 | using System.Net.Http;
6 | using System.Text;
7 | using System.Threading.Tasks;
8 |
9 | namespace NetDimension.OpenAuth
10 | {
11 | public abstract class OpenAuthenticationClientBase
12 | {
13 | public string ClientName { get; protected set; }
14 | public string ClientId { get; protected set; }
15 | public string ClientSecret { get; protected set; }
16 | public string CallbackUrl { get; protected set; }
17 | public string AccessToken { get; set; }
18 |
19 | public bool IsAuthorized
20 | {
21 | get { return isAccessTokenSet && !string.IsNullOrEmpty(AccessToken); }
22 | }
23 |
24 | protected abstract string BaseApiUrl { get; }
25 |
26 | protected bool isAccessTokenSet = false;
27 | protected abstract string AuthorizationCodeUrl { get; }
28 | protected abstract string AccessTokenUrl { get; }
29 | public abstract string GetAuthorizationUrl();
30 |
31 | public abstract void GetAccessTokenByCode(string code);
32 |
33 | protected HttpClient http;
34 |
35 |
36 | public HttpResponseMessage HttpGet(string api, dynamic parameters)
37 | {
38 | return HttpGetAsync(api, parameters).Result;
39 | }
40 |
41 | public Task HttpGetAsync(string api, dynamic parameters)
42 | {
43 | var paramType = ((object)parameters).GetType();
44 | if (!(paramType.Name.Contains("AnonymousType") && paramType.IsSealed && paramType.Namespace == null))
45 | {
46 | throw new ArgumentException("只支持匿名类型参数");
47 | }
48 |
49 | var dict = paramType.GetProperties().Where(p => p.PropertyType.IsValueType || p.PropertyType == typeof(string)).ToDictionary(k => k.Name, v => string.Format("{0}", v.GetValue(parameters, null)));
50 |
51 | return HttpGetAsync(api, dict);
52 |
53 | }
54 |
55 |
56 | public HttpResponseMessage HttpGet(string api, Dictionary parameters = null)
57 | {
58 | return HttpGetAsync(api, parameters).Result;
59 | }
60 |
61 |
62 |
63 | public virtual Task HttpGetAsync(string api, Dictionary parameters = null)
64 | {
65 |
66 | if (parameters == null)
67 | parameters = new Dictionary();
68 |
69 | var queryString = string.Join("&", parameters.Where(p => p.Value == null || p.Value.GetType().IsValueType || p.Value.GetType() == typeof(string)).Select(p => string.Format("{0}={1}", Uri.EscapeDataString(p.Key), Uri.EscapeDataString(string.Format("{0}", p.Value)))));
70 |
71 | if (api.IndexOf("?") < 0)
72 | {
73 | api = string.Format("{0}?{1}", api, queryString);
74 | }
75 | else
76 | {
77 | api = string.Format("{0}&{1}", api, queryString);
78 | }
79 |
80 | api = api.Trim('&', '?');
81 |
82 | return http.GetAsync(api);
83 | }
84 |
85 | public HttpResponseMessage HttpPost(string api, dynamic parameters)
86 | {
87 |
88 | return HttpPostAsync(api, parameters).Result;
89 |
90 | }
91 |
92 | public Task HttpPostAsync(string api, dynamic parameters)
93 | {
94 | var paramType = ((object)parameters).GetType();
95 | if (!(paramType.Name.Contains("AnonymousType") && paramType.IsSealed && paramType.Namespace == null))
96 | {
97 | throw new ArgumentException("只支持匿名类型参数");
98 | }
99 |
100 | var dict = paramType.GetProperties().ToDictionary(k => k.Name, v => v.GetValue((object)parameters, null));
101 |
102 | return HttpPostAsync(api, dict);
103 | }
104 |
105 |
106 | public HttpResponseMessage HttpPost(string api, Dictionary parameters)
107 | {
108 |
109 | return HttpPostAsync(api, parameters).Result;
110 | }
111 |
112 | public virtual Task HttpPostAsync(string api, Dictionary parameters)
113 | {
114 | if (parameters == null)
115 | {
116 | parameters = new Dictionary();
117 | }
118 |
119 | var dict = new Dictionary(parameters.ToDictionary(k => k.Key, v => v.Value));
120 |
121 | HttpContent httpContent = null;
122 |
123 | if (dict.Count(p => p.Value.GetType() == typeof(byte[]) ||
124 | p.Value.GetType() == typeof(System.IO.FileInfo)) > 0)
125 | {
126 | var content = new MultipartFormDataContent();
127 |
128 | foreach (var param in dict)
129 | {
130 | var dataType = param.Value.GetType();
131 | if (dataType == typeof(byte[])) //byte[]
132 | {
133 | content.Add(new ByteArrayContent((byte[])param.Value), param.Key, GetNonceString());
134 | }
135 | else if (dataType == typeof(MemoryFileContent)) //内存文件
136 | {
137 | var mcontent = (MemoryFileContent)param.Value;
138 | content.Add(new ByteArrayContent(mcontent.Content), param.Key, mcontent.FileName);
139 | }
140 | else if (dataType == typeof(System.IO.FileInfo)) //本地文件
141 | {
142 | var file = (System.IO.FileInfo)param.Value;
143 | content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(file.FullName)), param.Key, file.Name);
144 | }
145 | else /*if (dataType.IsValueType || dataType == typeof(string))*/ //其他类型
146 | {
147 | content.Add(new StringContent(string.Format("{0}", param.Value)), param.Key);
148 | }
149 |
150 |
151 | }
152 |
153 | httpContent = content;
154 |
155 | }
156 | else
157 | {
158 | var content = new FormUrlEncodedContent(dict.ToDictionary(k => k.Key, v => string.Format("{0}", v.Value)));
159 | httpContent = content;
160 | }
161 |
162 |
163 |
164 |
165 | return http.PostAsync(api, httpContent);
166 | }
167 |
168 | public OpenAuthenticationClientBase(string clientId, string clientSecret, string callbackUrl, string accessToken = null)
169 | {
170 | this.ClientId = clientId;
171 | this.ClientSecret = clientSecret;
172 | this.CallbackUrl = callbackUrl;
173 | this.AccessToken = accessToken;
174 |
175 |
176 | var handler = new HttpClientHandler()
177 | {
178 | CookieContainer = new CookieContainer(),
179 | UseCookies = true
180 | };
181 |
182 | http = new HttpClient(handler)
183 | {
184 | BaseAddress = new Uri(BaseApiUrl),
185 | };
186 |
187 | if (!string.IsNullOrEmpty(accessToken))
188 | {
189 | isAccessTokenSet = true;
190 | }
191 | }
192 |
193 |
194 | private string GetNonceString(int length = 8)
195 | {
196 | var sb = new StringBuilder();
197 |
198 | var rnd = new Random();
199 | for (var i = 0; i < length; i++)
200 | {
201 |
202 | sb.Append((char)rnd.Next(97, 123));
203 |
204 | }
205 |
206 | return sb.ToString();
207 |
208 | }
209 |
210 | }
211 | }
212 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("NetDimension.OpenAuth")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Net Dimension Studio")]
12 | [assembly: AssemblyProduct("NetDimension.OpenAuth")]
13 | [assembly: AssemblyCopyright("Copyright © Net Dimension Studio 2015")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("9da79205-1433-42cc-9dd7-6c1913d431d6")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/NetDimension.OpenAuth/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # WeiboSDK
2 | ## 新浪微博SDK v3 源码和示例
3 |
4 | ### 前言
5 | 时间过得飞快,距离上次SDK更新已经3年有余。随着官方的不断跟新,老版SDK的部分接口已经不能正常使用。因此在QQ群里来吐槽的、来谩骂的朋友也开始多了起来。随着时代的发展,微博已经彻底的被微信甩开,因此对它的兴趣已经丧失;同时对我自己来说,那么几年在行业里面为了生存而奔波,日子越混越差,已经无暇再与新浪官方同步更新SDK,因此自从13年以后就再也没有更新过V2版的SDK。虽然微博大势已去,但是依然有很多朋友通过新浪开放平台的页面下载了我发布的这个SDK,可以说,由于长时间的不更新,老版本已经严重误导了新来的朋友,这也是我开发了新版SDK的另外一个重要原因。
6 | 第三版SDK的一些说明
7 | * 与老版本不兼容
8 | * 不再支持.NET 4.0以下的版本
9 | * 没有封装官方API,但新版接口调用规范遵循新浪官方API的参数风格,具体请看示例
10 | 其他提示
11 | * 第三版SDK基于微软的HTTP Client Libraries,并且不再内部封装JSON.Net,新建项目请自行Nuget。
12 | * 由于新浪的限制,第三版SDK不再提供模拟登录接口,Winform或者控制台项目请引用NetDimension.OpenAuth.Winform库,里面封装了一个授权窗口,具体请看示例。
13 |
14 | ### 使用方法
15 | 第一步,初始化客户端
16 |
17 | 如果用户还未进行授权的情况
18 |
19 | 使用微博开放平台后台中提供的appkey,appsecret以及回调地址callback_url来初始化客户端。
20 |
21 | var openAuth = new SinaWeiboClient("", "", "");
22 |
23 | 然后取得授权页面地址,并访问该地址进行授权,并获得Authorization_Code
24 |
25 | var url = openAuth.GetAuthorizationUrl();
26 |
27 | 根据返回的Code换取AccessToken
28 |
29 |
30 | openAuth.GetAccessTokenByCode("[CODE]");
31 | if(openAuth.IsAuthorized)
32 | {
33 | var accessToken = openAuth.AccessToken;
34 | var uid = openAuth.UID;
35 | }
36 |
37 | 重要!!!获得了AccessToken和UID后请保存好这两个数据,以后的接口调用直接使用这两个参数,就不用每次都执行第一步和第二步。
38 |
39 | 下面,就可以跳转到第二步来调用官方的API了。
40 |
41 | 当然,如果之前已经进行过授权,并且已获得AccessToken和UID,使用下面的方法来初始化客户端。
42 |
43 | var openAuth = new SinaWeiboClient("", "", "", "");
44 |
45 | 之后就可以直接跳转到第二步来调用API了。
46 |
47 | 第二步,调用接口
48 |
49 | 这里提供了Get和Post两个方法来调用官方的API,同时提供了异步的支持。使用的时候根据官方文档的要求来选择使用Get还是Post来调用API(官方的文档中已经明确说明了调用方式)。
50 |
51 | 调用接口传参的方式有两个,一种是传一个Dictionary类型的参数组进去,另外一个是new一个匿名类传进去,个人觉得用匿名类才会显得非常科学。
52 |
53 | 例如,调用获取当前登录用户最新微博的API
54 |
55 | var result = openAuth.HttpGet("statuses/friends_timeline.json",
56 | new Dictionary
57 | {
58 | {"count", 5},
59 | {"page", 1},
60 | {"base_app" , 0}
61 | }); //这里可以使用字典或者匿名类的方式传递参数,参数名称、大小写、参数顺序和规范请参照官方api文档
62 |
63 | if (result.IsSuccessStatusCode)
64 | {
65 | Console.WriteLine(result.Content.ReadAsStringAsync().Result);
66 | }
67 |
68 | 另外,如果需要异步调用请参考下面的例子。
69 |
70 | // 调用获取获取用户信息api
71 | // 参考:http://open.weibo.com/wiki/2/users/show
72 | var response = openAuth.HttpGetAsync("users/show.json",
73 | //可以传入一个Dictionary类型的对象,也可以直接传入一个匿名类。参数与官方api文档中的参数相对应
74 | new {
75 | uid = openAuth.UID
76 | });
77 |
78 | response.ContinueWith(task =>{
79 | //异步处理结果
80 | });
81 |
82 | 如果使用.net4.5的话,是可以直接使用async和await关键字来简化上面的操作的。
83 |
84 | 另外,因为现在新浪官方的限制搞出了个登录验证码,所以新版的SDK就不再提供以前版本的模拟登录来获取授权(ClientLogin)方式。针对Winform和Console应用,可以引用NetDimension.OpenAuth.Winform这个类,其中提供了一个扩展方法可以在上述两种项目类型中弹出授权窗口,并在用户授权后自动获得Authorization_Code,具体操作请查看Winform和Console的示例代码。
85 |
86 | using NetDimension.OpenAuth.Winform;
87 |
88 | ...
89 |
90 | var form = openAuth.GetAuthenticationForm();
91 | if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
92 | {
93 | Console.WriteLine("用户授权成功!");
94 | var accessToken = openAuth.AccessToken;
95 | var uid = openAuth.UID;
96 | //其他操作
97 | //...
98 |
99 | }
100 | else
101 | {
102 | Console.WriteLine("用户授权失败!");
103 | }
104 |
105 | 执行上面的代码,将弹出下图所示的窗口。
106 |
107 | 
108 |
109 | 用户完成登录后,SDK会使用正则表达式从回调地址中获取Authorization_Code。
110 |
111 | ### 关于源代码中的示例
112 |
113 | 示例没啥好说的,源码中有三个示例,分别是一个MVC的网页示例,两个桌面的控制台和WinForm示例。
114 |
115 | 示例里面明文写了一套APPKey和对应的Secret及回调地址,不改的话示例应该是可以正常运行的,如果改成自己的Key以后出错,那么就请自行Google如何设置回调地址。
116 |
117 | MVC的示例设置稍微复杂点,要去改下IIS Express的配置,让网站能通过127.0.0.1或者192.168.0.100这样的IP地址访问到,不然回调的时候无法访问到,MVC示例的首页上有修改教程,如果示例运行不起来请打开Views\Home\Index.cshtml看如果修改。
118 |
119 | Winform示例运行截图
120 |
121 | 
122 |
123 | 
124 |
125 | 网站示例运行截图
126 | 
127 | 另外需要注意的是,如果使用的是VS2015,IIS Express的配置文件applicationhost.config地址已经不再是“文档\IIS Express\”,而是在项目地址下的.vs目录下,该目录是个隐藏目录,直接地址栏里面输入路径来访问。
128 |
129 | 控制台示例运行截图
130 | 
131 | 示例中有调用腾讯微博的例子,但是腾讯的要求很严,申请app需要网站验证,因为我用朋友的网站,所以请有需要的朋友还是自行注册app(腾讯微博的开发者平台dev.t.qq.com的api文档服务器是不是挂了?反正我是上不去了。)。另外,腾讯的例子里有个发图片微博的方法,严格按照腾讯api文档来写的,但是不能正常使用,如果有朋友知道原因还请告知。写腾讯的例子,只是为了展示新版的SDK通过继承,很容易就可以拓展到其他诸如微信开放平台、人人等平台。具体要怎么用,大家自行发掘。
132 |
133 | 示例的代码已经包含在源代码里,具体请自行参考代码。
134 |
135 |
136 |
137 | 以上,就是新版本的所有内容。
138 |
139 | 正如开篇所说的,新浪微博感觉大势已去,所以这个微博SDK也不会再更新新版本。第三版的这个SDK将最为最终版本,只做维护和BUG修正,不再增加和更新新内容。如果有朋友对新浪开发平台继续保持着兴趣,请自行GitHub去Clone代码,按自己的需求去扩展功能。
140 |
141 | 最后,感谢QQ群里面的所有朋友这么几年以来的支持和鼓舞,谢谢。
142 |
--------------------------------------------------------------------------------
/WeiboSDK.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.24720.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetDimension.OpenAuth", "NetDimension.OpenAuth\NetDimension.OpenAuth.csproj", "{38B68338-7FC0-4AB7-B8A7-674E0BCBF899}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetDimension.OpenAuth.Sina", "NetDimension.OpenAuth.Sina\NetDimension.OpenAuth.Sina.csproj", "{76FC909D-BDA2-4FCE-9B9F-B503A13DF44F}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetDimension.OpenAuth.Tencent", "NetDimension.OpenAuth.Tencent\NetDimension.OpenAuth.Tencent.csproj", "{DF5550C5-B4E3-4697-87B7-F6182DBFBC6F}"
11 | EndProject
12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{8664F01B-C592-4E8D-BD64-42B8DBBEFE5B}"
13 | ProjectSection(SolutionItems) = preProject
14 | .nuget\NuGet.Config = .nuget\NuGet.Config
15 | .nuget\NuGet.exe = .nuget\NuGet.exe
16 | .nuget\NuGet.targets = .nuget\NuGet.targets
17 | EndProjectSection
18 | EndProject
19 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleDemo", "ConsoleDemo\ConsoleDemo.csproj", "{DC434F36-8A91-48A7-BF76-BE72FFDF0C71}"
20 | EndProject
21 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetDimension.OpenAuth.Winform", "NetDimension.OpenAuth.Winform\NetDimension.OpenAuth.Winform.csproj", "{0D1F893B-AF94-4E52-B972-A5D40E1DB670}"
22 | EndProject
23 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinformDemo", "WinformDemo\WinformDemo.csproj", "{5D818E92-52D8-4643-B6BC-23AAD790B311}"
24 | EndProject
25 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MvcDemo", "MvcDemo\MvcDemo.csproj", "{C4F823E1-D35F-4B93-9AB8-B2D9D64C15FD}"
26 | EndProject
27 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "git", "git", "{02324A68-AE36-4843-9473-C1EAC6C3EDDB}"
28 | ProjectSection(SolutionItems) = preProject
29 | LICENSE = LICENSE
30 | README.md = README.md
31 | EndProjectSection
32 | EndProject
33 | Global
34 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
35 | Debug|Any CPU = Debug|Any CPU
36 | Release|Any CPU = Release|Any CPU
37 | EndGlobalSection
38 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
39 | {38B68338-7FC0-4AB7-B8A7-674E0BCBF899}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
40 | {38B68338-7FC0-4AB7-B8A7-674E0BCBF899}.Debug|Any CPU.Build.0 = Debug|Any CPU
41 | {38B68338-7FC0-4AB7-B8A7-674E0BCBF899}.Release|Any CPU.ActiveCfg = Release|Any CPU
42 | {38B68338-7FC0-4AB7-B8A7-674E0BCBF899}.Release|Any CPU.Build.0 = Release|Any CPU
43 | {76FC909D-BDA2-4FCE-9B9F-B503A13DF44F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
44 | {76FC909D-BDA2-4FCE-9B9F-B503A13DF44F}.Debug|Any CPU.Build.0 = Debug|Any CPU
45 | {76FC909D-BDA2-4FCE-9B9F-B503A13DF44F}.Release|Any CPU.ActiveCfg = Release|Any CPU
46 | {76FC909D-BDA2-4FCE-9B9F-B503A13DF44F}.Release|Any CPU.Build.0 = Release|Any CPU
47 | {DF5550C5-B4E3-4697-87B7-F6182DBFBC6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
48 | {DF5550C5-B4E3-4697-87B7-F6182DBFBC6F}.Debug|Any CPU.Build.0 = Debug|Any CPU
49 | {DF5550C5-B4E3-4697-87B7-F6182DBFBC6F}.Release|Any CPU.ActiveCfg = Release|Any CPU
50 | {DF5550C5-B4E3-4697-87B7-F6182DBFBC6F}.Release|Any CPU.Build.0 = Release|Any CPU
51 | {DC434F36-8A91-48A7-BF76-BE72FFDF0C71}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
52 | {DC434F36-8A91-48A7-BF76-BE72FFDF0C71}.Debug|Any CPU.Build.0 = Debug|Any CPU
53 | {DC434F36-8A91-48A7-BF76-BE72FFDF0C71}.Release|Any CPU.ActiveCfg = Release|Any CPU
54 | {DC434F36-8A91-48A7-BF76-BE72FFDF0C71}.Release|Any CPU.Build.0 = Release|Any CPU
55 | {0D1F893B-AF94-4E52-B972-A5D40E1DB670}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
56 | {0D1F893B-AF94-4E52-B972-A5D40E1DB670}.Debug|Any CPU.Build.0 = Debug|Any CPU
57 | {0D1F893B-AF94-4E52-B972-A5D40E1DB670}.Release|Any CPU.ActiveCfg = Release|Any CPU
58 | {0D1F893B-AF94-4E52-B972-A5D40E1DB670}.Release|Any CPU.Build.0 = Release|Any CPU
59 | {5D818E92-52D8-4643-B6BC-23AAD790B311}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
60 | {5D818E92-52D8-4643-B6BC-23AAD790B311}.Debug|Any CPU.Build.0 = Debug|Any CPU
61 | {5D818E92-52D8-4643-B6BC-23AAD790B311}.Release|Any CPU.ActiveCfg = Release|Any CPU
62 | {5D818E92-52D8-4643-B6BC-23AAD790B311}.Release|Any CPU.Build.0 = Release|Any CPU
63 | {C4F823E1-D35F-4B93-9AB8-B2D9D64C15FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
64 | {C4F823E1-D35F-4B93-9AB8-B2D9D64C15FD}.Debug|Any CPU.Build.0 = Debug|Any CPU
65 | {C4F823E1-D35F-4B93-9AB8-B2D9D64C15FD}.Release|Any CPU.ActiveCfg = Release|Any CPU
66 | {C4F823E1-D35F-4B93-9AB8-B2D9D64C15FD}.Release|Any CPU.Build.0 = Release|Any CPU
67 | EndGlobalSection
68 | GlobalSection(SolutionProperties) = preSolution
69 | HideSolutionNode = FALSE
70 | EndGlobalSection
71 | EndGlobal
72 |
--------------------------------------------------------------------------------
/WinformDemo/Form1.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace WinformDemo
2 | {
3 | partial class Form1
4 | {
5 | ///
6 | /// 必需的设计器变量。
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// 清理所有正在使用的资源。
12 | ///
13 | /// 如果应释放托管资源,为 true;否则为 false。
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Windows 窗体设计器生成的代码
24 |
25 | ///
26 | /// 设计器支持所需的方法 - 不要
27 | /// 使用代码编辑器修改此方法的内容。
28 | ///
29 | private void InitializeComponent()
30 | {
31 | System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
32 | this.picAvatar = new System.Windows.Forms.PictureBox();
33 | this.lblName = new System.Windows.Forms.Label();
34 | this.lblLocation = new System.Windows.Forms.Label();
35 | this.lblDescription = new System.Windows.Forms.Label();
36 | this.statusPanel = new System.Windows.Forms.Panel();
37 | this.txtStatus = new System.Windows.Forms.TextBox();
38 | this.lblCharCount = new System.Windows.Forms.Label();
39 | this.btnAddImage = new System.Windows.Forms.Button();
40 | this.btnCloseStatusPanel = new System.Windows.Forms.Button();
41 | this.btnPost = new System.Windows.Forms.Button();
42 | this.btnShowStatusPanel = new System.Windows.Forms.Button();
43 | this.webBrowser1 = new System.Windows.Forms.WebBrowser();
44 | this.lblState = new System.Windows.Forms.Label();
45 | ((System.ComponentModel.ISupportInitialize)(this.picAvatar)).BeginInit();
46 | this.statusPanel.SuspendLayout();
47 | this.SuspendLayout();
48 | //
49 | // picAvatar
50 | //
51 | this.picAvatar.BackColor = System.Drawing.Color.Transparent;
52 | this.picAvatar.Cursor = System.Windows.Forms.Cursors.Hand;
53 | this.picAvatar.Location = new System.Drawing.Point(12, 12);
54 | this.picAvatar.Name = "picAvatar";
55 | this.picAvatar.Size = new System.Drawing.Size(100, 100);
56 | this.picAvatar.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
57 | this.picAvatar.TabIndex = 0;
58 | this.picAvatar.TabStop = false;
59 | this.picAvatar.Click += new System.EventHandler(this.picAvatar_Click);
60 | //
61 | // lblName
62 | //
63 | this.lblName.AutoSize = true;
64 | this.lblName.BackColor = System.Drawing.Color.Transparent;
65 | this.lblName.Font = new System.Drawing.Font("微软雅黑", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
66 | this.lblName.ForeColor = System.Drawing.Color.White;
67 | this.lblName.Location = new System.Drawing.Point(125, 12);
68 | this.lblName.Margin = new System.Windows.Forms.Padding(10, 0, 3, 10);
69 | this.lblName.Name = "lblName";
70 | this.lblName.Size = new System.Drawing.Size(103, 25);
71 | this.lblName.TabIndex = 1;
72 | this.lblName.Text = "正在加载...";
73 | //
74 | // lblLocation
75 | //
76 | this.lblLocation.AutoSize = true;
77 | this.lblLocation.BackColor = System.Drawing.Color.Transparent;
78 | this.lblLocation.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(41)))), ((int)(((byte)(71)))), ((int)(((byte)(87)))));
79 | this.lblLocation.Location = new System.Drawing.Point(234, 18);
80 | this.lblLocation.Name = "lblLocation";
81 | this.lblLocation.Size = new System.Drawing.Size(56, 17);
82 | this.lblLocation.TabIndex = 2;
83 | this.lblLocation.Text = "正在加载";
84 | //
85 | // lblDescription
86 | //
87 | this.lblDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
88 | | System.Windows.Forms.AnchorStyles.Right)));
89 | this.lblDescription.BackColor = System.Drawing.Color.Transparent;
90 | this.lblDescription.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(206)))), ((int)(((byte)(230)))), ((int)(((byte)(243)))));
91 | this.lblDescription.Location = new System.Drawing.Point(127, 58);
92 | this.lblDescription.Name = "lblDescription";
93 | this.lblDescription.Size = new System.Drawing.Size(219, 54);
94 | this.lblDescription.TabIndex = 2;
95 | this.lblDescription.Text = "正在加载";
96 | //
97 | // statusPanel
98 | //
99 | this.statusPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
100 | | System.Windows.Forms.AnchorStyles.Right)));
101 | this.statusPanel.BackColor = System.Drawing.Color.White;
102 | this.statusPanel.Controls.Add(this.txtStatus);
103 | this.statusPanel.Controls.Add(this.lblCharCount);
104 | this.statusPanel.Controls.Add(this.btnAddImage);
105 | this.statusPanel.Controls.Add(this.btnCloseStatusPanel);
106 | this.statusPanel.Controls.Add(this.btnPost);
107 | this.statusPanel.Location = new System.Drawing.Point(12, 12);
108 | this.statusPanel.Name = "statusPanel";
109 | this.statusPanel.Size = new System.Drawing.Size(440, 100);
110 | this.statusPanel.TabIndex = 3;
111 | this.statusPanel.Visible = false;
112 | //
113 | // txtStatus
114 | //
115 | this.txtStatus.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
116 | | System.Windows.Forms.AnchorStyles.Left)
117 | | System.Windows.Forms.AnchorStyles.Right)));
118 | this.txtStatus.BorderStyle = System.Windows.Forms.BorderStyle.None;
119 | this.txtStatus.Font = new System.Drawing.Font("微软雅黑", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
120 | this.txtStatus.Location = new System.Drawing.Point(3, 3);
121 | this.txtStatus.Multiline = true;
122 | this.txtStatus.Name = "txtStatus";
123 | this.txtStatus.Size = new System.Drawing.Size(434, 53);
124 | this.txtStatus.TabIndex = 0;
125 | this.txtStatus.TextChanged += new System.EventHandler(this.txtStatus_TextChanged);
126 | this.txtStatus.Enter += new System.EventHandler(this.txtStatus_Enter);
127 | this.txtStatus.Leave += new System.EventHandler(this.txtStatus_Leave);
128 | //
129 | // lblCharCount
130 | //
131 | this.lblCharCount.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
132 | | System.Windows.Forms.AnchorStyles.Right)));
133 | this.lblCharCount.BackColor = System.Drawing.Color.Transparent;
134 | this.lblCharCount.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
135 | this.lblCharCount.ForeColor = System.Drawing.Color.DarkGray;
136 | this.lblCharCount.Location = new System.Drawing.Point(44, 62);
137 | this.lblCharCount.Name = "lblCharCount";
138 | this.lblCharCount.Size = new System.Drawing.Size(226, 30);
139 | this.lblCharCount.TabIndex = 3;
140 | this.lblCharCount.Text = "还可以输入140字";
141 | this.lblCharCount.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
142 | //
143 | // btnAddImage
144 | //
145 | this.btnAddImage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
146 | this.btnAddImage.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
147 | this.btnAddImage.Image = global::WinformDemo.Properties.Resources.image_add;
148 | this.btnAddImage.Location = new System.Drawing.Point(8, 62);
149 | this.btnAddImage.Name = "btnAddImage";
150 | this.btnAddImage.Size = new System.Drawing.Size(30, 30);
151 | this.btnAddImage.TabIndex = 2;
152 | this.btnAddImage.UseMnemonic = false;
153 | this.btnAddImage.UseVisualStyleBackColor = false;
154 | this.btnAddImage.Click += new System.EventHandler(this.btnAddImage_Click);
155 | //
156 | // btnCloseStatusPanel
157 | //
158 | this.btnCloseStatusPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
159 | this.btnCloseStatusPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(217)))), ((int)(((byte)(102)))), ((int)(((byte)(141)))));
160 | this.btnCloseStatusPanel.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
161 | this.btnCloseStatusPanel.ForeColor = System.Drawing.Color.White;
162 | this.btnCloseStatusPanel.Location = new System.Drawing.Point(357, 62);
163 | this.btnCloseStatusPanel.Name = "btnCloseStatusPanel";
164 | this.btnCloseStatusPanel.Size = new System.Drawing.Size(75, 30);
165 | this.btnCloseStatusPanel.TabIndex = 1;
166 | this.btnCloseStatusPanel.Text = "关闭";
167 | this.btnCloseStatusPanel.UseMnemonic = false;
168 | this.btnCloseStatusPanel.UseVisualStyleBackColor = false;
169 | this.btnCloseStatusPanel.Click += new System.EventHandler(this.btnCloseStatusPanel_Click);
170 | //
171 | // btnPost
172 | //
173 | this.btnPost.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
174 | this.btnPost.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(110)))), ((int)(((byte)(159)))));
175 | this.btnPost.Enabled = false;
176 | this.btnPost.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
177 | this.btnPost.ForeColor = System.Drawing.Color.White;
178 | this.btnPost.Location = new System.Drawing.Point(276, 62);
179 | this.btnPost.Name = "btnPost";
180 | this.btnPost.Size = new System.Drawing.Size(75, 30);
181 | this.btnPost.TabIndex = 1;
182 | this.btnPost.Text = "发布";
183 | this.btnPost.UseMnemonic = false;
184 | this.btnPost.UseVisualStyleBackColor = false;
185 | this.btnPost.Click += new System.EventHandler(this.btnPost_Click);
186 | //
187 | // btnShowStatusPanel
188 | //
189 | this.btnShowStatusPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
190 | this.btnShowStatusPanel.BackColor = System.Drawing.Color.Transparent;
191 | this.btnShowStatusPanel.FlatAppearance.BorderSize = 0;
192 | this.btnShowStatusPanel.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
193 | this.btnShowStatusPanel.Image = global::WinformDemo.Properties.Resources.paperfly;
194 | this.btnShowStatusPanel.Location = new System.Drawing.Point(352, 12);
195 | this.btnShowStatusPanel.Name = "btnShowStatusPanel";
196 | this.btnShowStatusPanel.Size = new System.Drawing.Size(100, 100);
197 | this.btnShowStatusPanel.TabIndex = 4;
198 | this.btnShowStatusPanel.UseVisualStyleBackColor = false;
199 | this.btnShowStatusPanel.Click += new System.EventHandler(this.btnShowStatusPanel_Click);
200 | //
201 | // webBrowser1
202 | //
203 | this.webBrowser1.AllowWebBrowserDrop = false;
204 | this.webBrowser1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
205 | | System.Windows.Forms.AnchorStyles.Left)
206 | | System.Windows.Forms.AnchorStyles.Right)));
207 | this.webBrowser1.IsWebBrowserContextMenuEnabled = false;
208 | this.webBrowser1.Location = new System.Drawing.Point(12, 118);
209 | this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
210 | this.webBrowser1.Name = "webBrowser1";
211 | this.webBrowser1.ScriptErrorsSuppressed = true;
212 | this.webBrowser1.Size = new System.Drawing.Size(440, 551);
213 | this.webBrowser1.TabIndex = 5;
214 | this.webBrowser1.WebBrowserShortcutsEnabled = false;
215 | //
216 | // lblState
217 | //
218 | this.lblState.AutoSize = true;
219 | this.lblState.BackColor = System.Drawing.Color.Transparent;
220 | this.lblState.ForeColor = System.Drawing.Color.DimGray;
221 | this.lblState.Location = new System.Drawing.Point(127, 36);
222 | this.lblState.Name = "lblState";
223 | this.lblState.Size = new System.Drawing.Size(0, 17);
224 | this.lblState.TabIndex = 6;
225 | //
226 | // Form1
227 | //
228 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
229 | this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(218)))), ((int)(((byte)(239)))));
230 | this.BackgroundImage = global::WinformDemo.Properties.Resources.body_bg;
231 | this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
232 | this.ClientSize = new System.Drawing.Size(464, 681);
233 | this.Controls.Add(this.lblState);
234 | this.Controls.Add(this.webBrowser1);
235 | this.Controls.Add(this.lblDescription);
236 | this.Controls.Add(this.lblLocation);
237 | this.Controls.Add(this.lblName);
238 | this.Controls.Add(this.picAvatar);
239 | this.Controls.Add(this.btnShowStatusPanel);
240 | this.Controls.Add(this.statusPanel);
241 | this.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
242 | this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
243 | this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
244 | this.MaximizeBox = false;
245 | this.MaximumSize = new System.Drawing.Size(640, 2880);
246 | this.MinimumSize = new System.Drawing.Size(480, 720);
247 | this.Name = "Form1";
248 | this.Text = "微博DEMO";
249 | this.Load += new System.EventHandler(this.Form1_Load);
250 | ((System.ComponentModel.ISupportInitialize)(this.picAvatar)).EndInit();
251 | this.statusPanel.ResumeLayout(false);
252 | this.statusPanel.PerformLayout();
253 | this.ResumeLayout(false);
254 | this.PerformLayout();
255 |
256 | }
257 |
258 | #endregion
259 |
260 | private System.Windows.Forms.PictureBox picAvatar;
261 | private System.Windows.Forms.Label lblName;
262 | private System.Windows.Forms.Label lblLocation;
263 | private System.Windows.Forms.Label lblDescription;
264 | private System.Windows.Forms.Panel statusPanel;
265 | private System.Windows.Forms.Button btnAddImage;
266 | private System.Windows.Forms.Button btnPost;
267 | private System.Windows.Forms.TextBox txtStatus;
268 | private System.Windows.Forms.Label lblCharCount;
269 | private System.Windows.Forms.Button btnShowStatusPanel;
270 | private System.Windows.Forms.Button btnCloseStatusPanel;
271 | private System.Windows.Forms.WebBrowser webBrowser1;
272 | private System.Windows.Forms.Label lblState;
273 |
274 | }
275 | }
276 |
277 |
--------------------------------------------------------------------------------
/WinformDemo/Form1.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using Newtonsoft.Json.Linq;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.ComponentModel;
6 | using System.Data;
7 | using System.Diagnostics;
8 | using System.Drawing;
9 | using System.IO;
10 | using System.Linq;
11 | using System.Net.Http;
12 | using System.Text;
13 | using System.Text.RegularExpressions;
14 | using System.Threading.Tasks;
15 | using System.Windows.Forms;
16 |
17 | namespace WinformDemo
18 | {
19 | public partial class Form1 : Form
20 | {
21 |
22 | #region 微博列表的模板
23 | const string htmlPattern = @"
24 |
25 |
26 |
27 |
78 |
79 |
80 |
81 |
82 | ";
83 | const string imageParttern = @"
";
84 | const string statusPattern = @"
85 |
![]()
86 |
{1}:{2}
87 | {3}
88 |
转发({4}) 评论({5})
89 |
90 | ";
91 | const string repostPattern = @"
92 |
![]()
93 |
{1}:{2}
94 |
95 |
@{3}:{4}
96 | {5}
97 |
转发({6}) 评论({7})
98 |
99 |
转发({8}) 评论({9})
100 |
101 | ";
102 | #endregion
103 |
104 |
105 | private NetDimension.OpenAuth.Sina.SinaWeiboClient openAuth;
106 |
107 |
108 | bool statusIsOutOfRange;
109 |
110 | FileInfo imageFile = null;
111 |
112 | public Form1(NetDimension.OpenAuth.Sina.SinaWeiboClient client)
113 | {
114 | InitializeComponent();
115 | this.openAuth = client;
116 | }
117 |
118 | private void Form1_Load(object sender, EventArgs e)
119 | {
120 | GetUserInfo();
121 | lblCharCount.Text = GetContentLengthString(txtStatus.Text, out statusIsOutOfRange);
122 | GetFriendTimeline();
123 | }
124 | ///
125 | /// 获取用户信息
126 | ///
127 | ///
128 | private void GetUserInfo()
129 | {
130 | // 调用获取获取用户信息api
131 | // 参考:http://open.weibo.com/wiki/2/users/show
132 | var response = openAuth.HttpGet("users/show.json", new
133 | {
134 | //可以传入一个Dictionary类型的对象,也可以直接传入一个匿名类。参数与官方api文档中的参数相对应
135 | uid = openAuth.UID
136 | });
137 |
138 |
139 | Debug.WriteLine(response);
140 |
141 | if (response.IsSuccessStatusCode)
142 | {
143 | response.Content.ReadAsStringAsync().ContinueWith((task) =>
144 | {
145 | var json = JObject.Parse(task.Result);
146 | Debug.WriteLine(json);
147 |
148 |
149 | UpdateUI(() =>
150 | {
151 | picAvatar.ImageLocation = json.Value("avatar_large");
152 |
153 | lblName.Text = json.Value("screen_name");
154 |
155 | lblState.Text = string.Format("关注({0}) 粉丝({1})", json["friends_count"], json["followers_count"]);
156 |
157 | lblLocation.Text = json.Value("location");
158 |
159 | var g = Graphics.FromHwnd(this.Handle);
160 |
161 | var matrix = g.MeasureString(lblName.Text, lblName.Font);
162 |
163 |
164 |
165 | g.Dispose();
166 |
167 | lblLocation.Left = lblName.Left + (int)matrix.Width;
168 |
169 | lblDescription.Text = json.Value("description");
170 | });
171 |
172 |
173 |
174 |
175 |
176 | });
177 | }
178 | else
179 | {
180 | Debug.WriteLine(response.Content.ReadAsStringAsync().Result);
181 | }
182 |
183 | }
184 | ///
185 | /// 获取最新微博
186 | ///
187 | ///
188 | private void GetFriendTimeline()
189 | {
190 | // 调用获取当前登录用户及其所关注用户的最新微博api
191 | // 参考:http://open.weibo.com/wiki/2/statuses/friends_timeline
192 | openAuth.HttpGetAsync("statuses/home_timeline.json", new Dictionary
193 | {
194 | //可以传入一个Dictionary类型的对象,也可以直接传入一个匿名类。参数与官方api文档中的参数相对应
195 | {"count",10}
196 | }).ContinueWith(task =>
197 | {
198 |
199 | if (task.Result.IsSuccessStatusCode)
200 | {
201 | StringBuilder statusBuilder = new StringBuilder();
202 |
203 | //解析微博开放平台返回的json数据
204 | var json = JObject.Parse(task.Result.Content.ReadAsStringAsync().Result);
205 | Debug.WriteLine(json);
206 |
207 | foreach (JObject status in json.Value("statuses"))
208 | {
209 | if (status["user"] == null)
210 | continue;
211 |
212 | if (status["retweeted_status"] != null && status["retweeted_status"]["user"] != null)
213 | {
214 | statusBuilder.AppendFormat(repostPattern,
215 | status["user"]["profile_image_url"],
216 | status["user"]["screen_name"],
217 | status["text"],
218 | status["retweeted_status"]["user"]["screen_name"],
219 | status["retweeted_status"]["text"],
220 | status["retweeted_status"]["thumbnail_pic"] == null ? "" : string.Format(imageParttern, status["retweeted_status"]["thumbnail_pic"]),
221 | status["retweeted_status"]["reposts_count"],
222 | status["retweeted_status"]["comments_count"],
223 | status["reposts_count"],
224 | status["comments_count"]);
225 | }
226 | else
227 | {
228 | statusBuilder.AppendFormat(statusPattern,
229 | status["user"]["profile_image_url"],
230 | status["user"]["screen_name"],
231 | status["text"],
232 | status["thumbnail_pic"] == null ? "" : string.Format(imageParttern, status["thumbnail_pic"]),
233 | status["reposts_count"],
234 | status["comments_count"]);
235 | }
236 |
237 | }
238 |
239 | var html = htmlPattern.Replace("", statusBuilder.ToString());
240 |
241 | UpdateUI(() =>
242 | {
243 |
244 | webBrowser1.DocumentText = html;
245 |
246 | });
247 |
248 | }
249 | else
250 | {
251 | var reason = task.Result.Content.ReadAsStringAsync().Result;
252 | Debug.WriteLine(reason);
253 |
254 | webBrowser1.DocumentText = reason;
255 | }
256 |
257 | });
258 |
259 |
260 | }
261 |
262 | //多线程环境下修改主线程里面的控件需要用到此方法,如果用.net 4.5的await/async特性则无需此方法,具体请自己狗哥
263 | private void UpdateUI(Action uiAction)
264 | {
265 | if (this.InvokeRequired)
266 | {
267 | this.Invoke(new MethodInvoker(uiAction));
268 | }
269 | else
270 | {
271 | uiAction();
272 | }
273 | }
274 |
275 | private void picAvatar_Click(object sender, EventArgs e)
276 | {
277 | GetUserInfo();
278 | }
279 |
280 | //和官方一致的微博内容字数算法
281 | private string GetContentLengthString(string text, out bool isOutOfRange)
282 | {
283 | text = text.Trim();
284 | text = Regex.Replace(text, "\r\n", "\n");
285 | int textLength = 0;
286 | if (text.Length > 0)
287 | {
288 | int min = 41, max = 140, urlLen = 20;
289 | var n = text;
290 | var r = Regex.Matches(text, @"http://[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+([-A-Z0-9a-z_$.+!*()/\\\,:;@&=?~#%]*)*");
291 | var total = 0;
292 | for (int m = 0, p = r.Count; m < p; m++)
293 | {
294 | var url = r[m].Value;
295 | var byteLen = url.Length + Regex.Matches(url, @"[^\x00-\x80]").Count;
296 | if (Regex.IsMatch(url, @"^(http://t.cn)"))
297 | {
298 | continue;
299 | }
300 | else if (Regex.IsMatch(url, @"^(http:\/\/)+(weibo.com|weibo.cn)"))
301 | {
302 | total += byteLen <= min ? byteLen : (byteLen <= max ? urlLen : (byteLen - max + urlLen));
303 | }
304 | else
305 | {
306 | total += byteLen <= max ? urlLen : (byteLen - max + urlLen);
307 | }
308 | n = n.Replace(url, "");
309 | }
310 | textLength = (int)Math.Ceiling((total + n.Length + Regex.Matches(n, @"[^\x00-\x80]").Count) / 2.00d);
311 | }
312 |
313 | int textRemainLength = 140 - textLength;
314 | string template = string.Empty;
315 | if (textRemainLength >= 0)
316 | {
317 | template = "还可以输入{0:N0}个字";
318 | if (textLength == 0)
319 | {
320 | isOutOfRange = false;
321 | }
322 | else
323 | {
324 | isOutOfRange = true;
325 | }
326 |
327 | }
328 | else
329 | {
330 | template = "已经超过了{0:N0}个字";
331 |
332 | isOutOfRange = true;
333 | }
334 | return string.Format(template, Math.Abs(textRemainLength));
335 | }
336 |
337 | private void txtStatus_TextChanged(object sender, EventArgs e)
338 | {
339 | lblCharCount.Text = GetContentLengthString(txtStatus.Text, out statusIsOutOfRange);
340 |
341 | btnPost.Enabled = statusIsOutOfRange;
342 |
343 | }
344 |
345 | private void txtStatus_Enter(object sender, EventArgs e)
346 | {
347 | EnsureStatusPanelHeight();
348 | }
349 |
350 | private void txtStatus_Leave(object sender, EventArgs e)
351 | {
352 | EnsureStatusPanelHeight();
353 | }
354 |
355 | private void EnsureStatusPanelHeight()
356 | {
357 |
358 |
359 | }
360 |
361 | private void btnCloseStatusPanel_Click(object sender, EventArgs e)
362 | {
363 |
364 | statusPanel.Visible = false;
365 | imageFile = null;
366 | txtStatus.Text = string.Empty;
367 |
368 | }
369 |
370 | private void btnShowStatusPanel_Click(object sender, EventArgs e)
371 | {
372 | statusPanel.BringToFront();
373 | statusPanel.Visible = true;
374 | txtStatus.Focus();
375 |
376 | }
377 |
378 | private void btnAddImage_Click(object sender, EventArgs e)
379 | {
380 | var dlg = new OpenFileDialog
381 | {
382 | Filter = "支持的图片文件|*.png;*.jpg;*.jpeg;*.bmp;*.gif"
383 | };
384 |
385 | if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
386 | {
387 | imageFile = new FileInfo(dlg.FileName);
388 | }
389 | }
390 |
391 |
392 |
393 | private void btnPost_Click(object sender, EventArgs e)
394 | {
395 |
396 | statusPanel.Enabled = false;
397 |
398 | //发微博
399 |
400 |
401 | //带图的情况
402 | if (imageFile != null)
403 | {
404 | // 调用发图片微博api
405 | // 参考:http://open.weibo.com/wiki/2/statuses/upload
406 | openAuth.HttpPostAsync("statuses/upload.json", new Dictionary
407 | //当然,这里用匿名类也是可以的
408 | /*
409 | 匿名类传参方式:
410 | * new { status = txtStatus.Text, pic = imageFile }
411 | */
412 | {
413 |
414 | {"status" ,txtStatus.Text},
415 | {"pic" , imageFile} //imgFile: 对于文件上传,这里可以直接传FileInfo对象
416 | }).ContinueWith(task =>
417 | {
418 | //这里用了个异步方法,发微博不阻塞主线程,任务完成后调用处理方法
419 | StatusPosted(task);
420 | });
421 |
422 |
423 |
424 | }
425 | else
426 | {
427 | // 调用发微博api
428 | // 参考:http://open.weibo.com/wiki/2/statuses/update
429 | openAuth.HttpPostAsync("statuses/update.json", new
430 | {
431 | status = txtStatus.Text
432 | }).ContinueWith(task =>
433 | {
434 | StatusPosted(task);
435 | });
436 | }
437 | }
438 |
439 | //处理微博发送后的一些事情
440 | private void StatusPosted(Task task)
441 | {
442 | var result = task.Result;
443 | Debug.WriteLine(result);
444 |
445 | if (result.IsSuccessStatusCode)
446 | {
447 | //刷新微博内容
448 | GetFriendTimeline();
449 |
450 | //因为是异步,所以调用UpdateUI刷新界面
451 | UpdateUI(() =>
452 | {
453 |
454 | imageFile = null;
455 | txtStatus.Text = string.Empty;
456 |
457 | statusPanel.Enabled = true;
458 | statusPanel.Visible = false;
459 | });
460 | }
461 | else
462 | {
463 | UpdateUI(() =>
464 | {
465 | MessageBox.Show(this, string.Format("发布失败:\r\n{0}", result.Content.ReadAsStringAsync().Result), "发布失败", MessageBoxButtons.OK);
466 | statusPanel.Enabled = true;
467 | });
468 | }
469 | }
470 |
471 |
472 | }
473 | }
474 |
--------------------------------------------------------------------------------
/WinformDemo/Program.cs:
--------------------------------------------------------------------------------
1 | using NetDimension.OpenAuth.Sina;
2 | using NetDimension.OpenAuth.Winform;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Windows.Forms;
7 |
8 | namespace WinformDemo
9 | {
10 |
11 | static class Program
12 | {
13 |
14 |
15 |
16 | ///
17 | /// 应用程序的主入口点。
18 | ///
19 | [STAThread]
20 | static void Main()
21 | {
22 | Application.EnableVisualStyles();
23 | Application.SetCompatibleTextRenderingDefault(false);
24 |
25 |
26 | //请自行修改appKey,appSecret和回调地址。winform的回调地址可以是一个随便可以访问的地址,貌似不可以访问的地址也是可以的,只要URL中带着Code就行
27 | var client = new SinaWeiboClient("1402038860", "62e1ddd4f6bc33077c796d5129047ca2", "http://qcyn.sina.com.cn");
28 |
29 | //NetDimension.OpenAuth.Winform封装的一个登录窗口,主要远离就是个WebBrowser控件,然后在该控件的导航事件里面监测Url是不是带有Code,如果有就调用GetAccessTokenByCode
30 | var authForm = client.GetAuthenticationForm();
31 |
32 | authForm.StartPosition = FormStartPosition.CenterScreen;
33 | authForm.Icon = Properties.Resources.icon_form;
34 |
35 | if (authForm.ShowDialog() == DialogResult.OK)
36 | {
37 | Application.Run(new Form1(client));
38 | }
39 |
40 |
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/WinformDemo/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("WinformDemo")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Net Dimension Studio")]
12 | [assembly: AssemblyProduct("WinformDemo")]
13 | [assembly: AssemblyCopyright("Copyright © Net Dimension Studio 2015")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("142dd8b1-883b-4b10-a6ae-21678487adb2")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/WinformDemo/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本:4.0.30319.34209
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将会丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace WinformDemo.Properties {
12 | using System;
13 |
14 |
15 | ///
16 | /// 一个强类型的资源类,用于查找本地化的字符串等。
17 | ///
18 | // 此类是由 StronglyTypedResourceBuilder
19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
20 | // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
21 | // (以 /str 作为命令选项),或重新生成 VS 项目。
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// 返回此类使用的缓存的 ResourceManager 实例。
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WinformDemo.Properties.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// 使用此强类型资源类,为所有资源查找
51 | /// 重写当前线程的 CurrentUICulture 属性。
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 |
63 | ///
64 | /// 查找 System.Drawing.Bitmap 类型的本地化资源。
65 | ///
66 | internal static System.Drawing.Bitmap body_bg {
67 | get {
68 | object obj = ResourceManager.GetObject("body_bg", resourceCulture);
69 | return ((System.Drawing.Bitmap)(obj));
70 | }
71 | }
72 |
73 | ///
74 | /// 查找 System.Drawing.Bitmap 类型的本地化资源。
75 | ///
76 | internal static System.Drawing.Bitmap email {
77 | get {
78 | object obj = ResourceManager.GetObject("email", resourceCulture);
79 | return ((System.Drawing.Bitmap)(obj));
80 | }
81 | }
82 |
83 | ///
84 | /// 查找类似于 (Icon) 的 System.Drawing.Icon 类型的本地化资源。
85 | ///
86 | internal static System.Drawing.Icon icon_app {
87 | get {
88 | object obj = ResourceManager.GetObject("icon_app", resourceCulture);
89 | return ((System.Drawing.Icon)(obj));
90 | }
91 | }
92 |
93 | ///
94 | /// 查找类似于 (Icon) 的 System.Drawing.Icon 类型的本地化资源。
95 | ///
96 | internal static System.Drawing.Icon icon_form {
97 | get {
98 | object obj = ResourceManager.GetObject("icon_form", resourceCulture);
99 | return ((System.Drawing.Icon)(obj));
100 | }
101 | }
102 |
103 | ///
104 | /// 查找 System.Drawing.Bitmap 类型的本地化资源。
105 | ///
106 | internal static System.Drawing.Bitmap image_add {
107 | get {
108 | object obj = ResourceManager.GetObject("image_add", resourceCulture);
109 | return ((System.Drawing.Bitmap)(obj));
110 | }
111 | }
112 |
113 | ///
114 | /// 查找 System.Drawing.Bitmap 类型的本地化资源。
115 | ///
116 | internal static System.Drawing.Bitmap paperfly {
117 | get {
118 | object obj = ResourceManager.GetObject("paperfly", resourceCulture);
119 | return ((System.Drawing.Bitmap)(obj));
120 | }
121 | }
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/WinformDemo/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 |
122 | ..\Resources\body_bg.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
123 |
124 |
125 | ..\Resources\email.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
126 |
127 |
128 | ..\Resources\icon_app.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
129 |
130 |
131 | ..\Resources\icon_form.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
132 |
133 |
134 | ..\Resources\image_add.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
135 |
136 |
137 | ..\Resources\paperfly.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
138 |
139 |
--------------------------------------------------------------------------------
/WinformDemo/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.34209
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace WinformDemo.Properties
12 | {
13 |
14 |
15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
18 | {
19 |
20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
21 |
22 | public static Settings Default
23 | {
24 | get
25 | {
26 | return defaultInstance;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/WinformDemo/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/WinformDemo/Resources/body_bg.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/WinformDemo/Resources/body_bg.jpg
--------------------------------------------------------------------------------
/WinformDemo/Resources/email.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/WinformDemo/Resources/email.png
--------------------------------------------------------------------------------
/WinformDemo/Resources/icon_app.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/WinformDemo/Resources/icon_app.ico
--------------------------------------------------------------------------------
/WinformDemo/Resources/icon_form.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/WinformDemo/Resources/icon_form.ico
--------------------------------------------------------------------------------
/WinformDemo/Resources/image_add.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/WinformDemo/Resources/image_add.png
--------------------------------------------------------------------------------
/WinformDemo/Resources/paperfly.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NetDimension/WeiboSDK/9cdb3db53c407f9a8fe2252f720fe5557ba8d7a2/WinformDemo/Resources/paperfly.png
--------------------------------------------------------------------------------
/WinformDemo/WinformDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {5D818E92-52D8-4643-B6BC-23AAD790B311}
8 | WinExe
9 | Properties
10 | WinformDemo
11 | WinformDemo
12 | v4.0
13 | 512
14 | SAK
15 | SAK
16 | SAK
17 | SAK
18 | ..\
19 | true
20 |
21 |
22 | AnyCPU
23 | true
24 | full
25 | false
26 | bin\Debug\
27 | DEBUG;TRACE
28 | prompt
29 | 4
30 |
31 |
32 | AnyCPU
33 | pdbonly
34 | true
35 | bin\Release\
36 | TRACE
37 | prompt
38 | 4
39 |
40 |
41 |
42 | False
43 | ..\packages\Newtonsoft.Json.6.0.8\lib\net40\Newtonsoft.Json.dll
44 |
45 |
46 |
47 |
48 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.IO.dll
49 |
50 |
51 | False
52 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.dll
53 |
54 |
55 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.Extensions.dll
56 |
57 |
58 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.Primitives.dll
59 |
60 |
61 | False
62 | ..\packages\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.WebRequest.dll
63 |
64 |
65 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Runtime.dll
66 |
67 |
68 | ..\packages\Microsoft.Bcl.1.1.10\lib\net40\System.Threading.Tasks.dll
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 | Form
82 |
83 |
84 | Form1.cs
85 |
86 |
87 |
88 |
89 | Form1.cs
90 |
91 |
92 | ResXFileCodeGenerator
93 | Resources.Designer.cs
94 | Designer
95 |
96 |
97 | True
98 | Resources.resx
99 | True
100 |
101 |
102 |
103 |
104 | SettingsSingleFileGenerator
105 | Settings.Designer.cs
106 |
107 |
108 | True
109 | Settings.settings
110 | True
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 | {76fc909d-bda2-4fce-9b9f-b503a13df44f}
119 | NetDimension.OpenAuth.Sina
120 |
121 |
122 | {0d1f893b-af94-4e52-b972-a5d40e1db670}
123 | NetDimension.OpenAuth.Winform
124 |
125 |
126 | {38b68338-7fc0-4ab7-b8a7-674e0bcbf899}
127 | NetDimension.OpenAuth
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 | 这台计算机上缺少此项目引用的 NuGet 程序包。启用“NuGet 程序包还原”可下载这些程序包。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
165 |
--------------------------------------------------------------------------------
/WinformDemo/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/WinformDemo/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------