近期在开发一个项目需要使用结合微信公众号,于是使用了盛派的微信开发工具包。
参考了这篇文章:
https://www.cnblogs.com/szw/p/Wechat-MessageHandler-Middleware.html
Senparc.Weixin.MP SDK 微信公众平台开发教程(二十三):在 .NET Core 2.0/3.0 中使用 MessageHandler 中间件
使用中间件来响应微信公众号的消息 处理。
在startup.cs配置如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddSenparcWeixinServices(Configuration);//Senparc.Weixin 注册
}
configure中添加使用中间件:
app.UseMessageHandlerForMp("/WeixinAsync", CustomMpMessageHandler.GenerateMessageHandler, o => o.AccountSettingFunc = c => senparcWeixinSetting.Value);
继承消息处理事件代码如下:
using Microsoft.Extensions.Logging;
using NLog;
using Senparc.NeuChar.App.AppStore;
using Senparc.NeuChar.Entities;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MessageContexts;
using System;
using System.IO;
namespace NetCoreTFCMS.Common
{
/// <summary>
/// 自定义公众号消息处理
/// </summary>
public class CustomMpMessageHandler : Senparc.Weixin.MP.MessageHandlers.MessageHandler<DefaultMpMessageContext>
{
Logger glogger = LogManager.GetCurrentClassLogger();
public static Func<Stream, PostModel, int, CustomMpMessageHandler> GenerateMessageHandler = (stream, postModel, maxRecordCount)
=> new CustomMpMessageHandler(stream, postModel, maxRecordCount, false);
public CustomMpMessageHandler(Stream inputStream, PostModel postModel, int maxRecordCount = 0, bool onlyAllowEcryptMessage = false, DeveloperInfo developerInfo = null)
: base(inputStream, postModel, maxRecordCount, onlyAllowEcryptMessage, developerInfo)
{
}
public override IResponseMessageBase OnEventRequest(IRequestMessageEventBase requestMessage)
{
return base.OnEventRequest(requestMessage);
}
public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
{
var responseMessage = base.CreateResponseMessage<ResponseMessageNews>();
responseMessage.Articles.Add(new Article()
{
Title = $"消息类型:{requestMessage.MsgType},欢迎{requestMessage.FromUserName}关注{TF.GetConfig().WebTitle}",
Description = $"{TF.GetConfig().WebDescription}",
PicUrl = TF.GetConfig().WebLogo,
Url = TF.GetConfig().WebUrl
});
return responseMessage;
}
public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
{
var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = $"您发送了文字:{requestMessage.Content}";
glogger.Info($"您发送了文字:{requestMessage.Content}");
return responseMessage;
}
public override IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage)
{
var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = $"您发送了语音:{requestMessage.MediaId}";
return responseMessage;
}
}
}
都配置完,使用公众号发送消息,公众号只会收到默认DefaultResponseMessage的消息 响应。
重载的 OnTextRequest,OnVoiceRequest都没有任何反应,怎么解决呢?
用异步方法看一下。