现有的微信SDK库在 .NET Core 1.0 中表示很有压力,比如 Deepleo.Weixin.SDK 和 Senparc.Weixin(即使现有一个转移到.NET Core 1.0的初始项目,但是暂时还不能用) 。前者轻量后者全而轻便,但是按照我的个人观点看来,前者太轻便了,对于不记参数的我来说点不出来就等于白搭,后者需要自定义一个处理方法来执行相关任务,但是相关的类型对于我这个就爱点出来能解决的事绝不干多余的是的我来说,还是不大乐意去用。因此就结合两者自行开发一个适合自己使用的SDK库,在项目结束后开源。
附上现有的中间件Middleware的Demo
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading.Tasks; 5 using Microsoft.AspNetCore.Builder; 6 using Microsoft.AspNetCore.Http; 7 using WeChat; 8 using WeChat.Entities; 9 10 namespace WebApplication.Middleware 11 { 12 // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project 13 public class WeChatMiddleware 14 { 15 private readonly RequestDelegate _next; 16 17 public WeChatMiddleware(RequestDelegate next) 18 { 19 _next = next; 20 } 21 22 public async Task Invoke(HttpContext httpContext) 23 { 24 if (httpContext.Request.Path.Value.ToLower().EndsWith("/wxapi")) 25 { 26 #region Get 27 if (httpContext.Request.Method == "GET") 28 { 29 string echoString = httpContext.Request.Query["echoStr"]; 30 // 没有必要参数 直接忽略 31 if (string.IsNullOrWhiteSpace(echoString)) 32 await httpContext.Response.WriteAsync("( ̄▽ ̄) 你想干嘛"); 33 34 if (httpContext.CheckSignature(Option.WeChatConfig)) 35 await httpContext.Response.WriteAsync(echoString); 36 } 37 #endregion 38 #region POST 39 else if (httpContext.Request.Method == "POST") 40 { 41 string rsp = string.Empty; 42 var message = httpContext.GetMessage(Option.WeChatConfig); 43 if (message == null) return;//消息体验证失败或转换失败 终止处理 44 switch (message.Type) 45 { 46 case MessageType.Text: 47 switch (message.GetText()) 48 { 49 case "单图文": 50 rsp = message.ReplyNews(new News() { description = "测试", title = "测试图文" }); 51 break; 52 case "多图文": 53 rsp = message.ReplyNews( 54 new News() { description = "呵呵", title = "凸(艹皿艹 )", picurl = "url" }, 55 new News() { title = "阿勒", picurl = "url" } 56 ); 57 break; 58 default: 59 rsp = message.ReplyText("你发了:" + message.GetText()); 60 break; 61 } 62 break; 63 case MessageType.Event: 64 var evt = message.AsEvent(); 65 switch (evt.Event) 66 { 67 case Event.unsubscribe: return; 68 case Event.subscribe: 69 rsp = message.ReplyText("关注成功"); 70 break; 71 } 72 break; 73 default: 74 rsp = message.ReplyText("阿勒,你发了神马?"); 75 break; 76 } 77 await httpContext.FinalResponse(Option.WeChatConfig, rsp); return; //处理到此结束 直接返回消息 78 } 79 #endregion 80 // 默认不返回任何数据,以避免微信重复提交请求 81 return; 82 } 83 await _next(httpContext); 84 85 } 86 } 87 88 // Extension method used to add the middleware to the HTTP request pipeline. 89 public static class WeChatMiddlewareExtensions 90 { 91 public static IApplicationBuilder UseWeChatMiddleware(this IApplicationBuilder builder) 92 { 93 return builder.UseMiddleware<WeChatMiddleware>(); 94 } 95 } 96 }
时间: 2024-10-10 10:18:33