工具:
Visual Studio 2015 update 3
Asp.Net Core 1.0
1 準備工作
申請微信公眾平臺接口測試帳號,申請網址:(http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login)。申請接口測試號無需公眾帳號,可以直接體驗和測試公眾平臺所有高級接口。
1.1 配置接口信息

1.2 修改網頁授權信息

點擊“修改”后在彈出頁面填入你的網站域名:

2 新建網站項目
2.1 選擇ASP.NET Core Web Application 模板

2.2 選擇Web 應用程序,并更改身份驗證為個人用戶賬戶

3 集成微信登錄功能
3.1添加引用
打開project.json文件,添加引用Microsoft.AspNetCore.Authentication.OAuth

3.2 添加代碼文件
在項目中新建文件夾,命名為WeChatOAuth,并添加代碼文件(本文最后附全部代碼)。

3.3 注冊微信登錄中間件
打開Startup.cs文件,在Configure中添加代碼:
app.UseWeChatAuthentication(new WeChatOptions(){ AppId = "******", AppSecret = "******"});注意該代碼的插入位置必須在app.UseIdentity()下方。

4 代碼
WeChatAppBuilderExtensions.cs:
// Copyright (c) .NET Foundation. All rights reserved.// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.using System;using Microsoft.AspNetCore.Authentication.WeChat;using Microsoft.Extensions.Options;namespace Microsoft.AspNetCore.Builder{ /// <summary> /// Extension methods to add WeChat authentication capabilities to an HTTP application pipeline. /// </summary> public static class WeChatAppBuilderExtensions { /// <summary> /// Adds the <see cref="WeChatMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables WeChat authentication capabilities. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public static IApplicationBuilder UseWeChatAuthentication(this IApplicationBuilder app) { if (app == null) { throw new ArgumentNullException(nameof(app)); } return app.UseMiddleware<WeChatMiddleware>(); } /// <summary> /// Adds the <see cref="WeChatMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables WeChat authentication capabilities. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param> /// <param name="options">A <see cref="WeChatOptions"/> that specifies options for the middleware.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public static IApplicationBuilder UseWeChatAuthentication(this IApplicationBuilder app, WeChatOptions options) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } return app.UseMiddleware<WeChatMiddleware>(Options.Create(options)); } }}
新聞熱點
疑難解答
圖片精選