首页 > 编程 > .NET > 正文

ASP.NET Core集成微信登录

2024-07-10 12:46:44
字体:
来源:转载
供稿:网友

工具:

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));  } }}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表