.Net6+Furion+Sqlsugar+SenparcSdk开发微信公众号系列之四:自动回复

一、关于SenparcSdk的MessageHandler

参考:

Senparc.Weixin.MP SDK 微信公众平台开发教程(六):了解MessageHandler

Senparc.Weixin.MP SDK 微信公众平台开发教程(七):解决用户上下文(Session)问题

二、在项目中使用MessageHandler

WeiXinApi.Application新建Handler文件夹,并新建文件CustomMessageHandler

继承 MessageHandler<DefaultMpMessageContext>并实现抽象类

namespace WeiXinApi.Application.Handler

{

publicclass CustomMessageHandler : MessageHandler<DefaultMpMessageContext>

{

privatestring appId = Config.SenparcWeixinSetting.WeixinAppId;

privatestring appSecret = Config.SenparcWeixinSetting.WeixinAppSecret;

public CustomMessageHandler(Stream inputStream,

PostModel postModel,

int maxRecordCount = 0,

bool onlyAllowEncryptMessage = false,

Senparc.NeuChar.App.AppStore.DeveloperInfo developerInfo = null,

IServiceProvider serviceProvider = null)

: base(inputStream, postModel, maxRecordCount, onlyAllowEncryptMessage, developerInfo, serviceProvider)

{

//这里设置仅用于测试,实际开发可以在外部更全局的地方设置,

//比如MessageHandler<MessageContext>.GlobalGlobalMessageContext.ExpireMinutes = 3。

GlobalMessageContext.ExpireMinutes = 3;

OnlyAllowEncryptMessage = false;//是否只允许接收加密消息,默认为 falseif (!string.IsNullOrEmpty(postModel.AppId))

{

appId = postModel.AppId;//通过第三方开放平台发送过来的请求 }

//在指定条件下,不使用消息去重base.OmitRepeatedMessageFunc = requestMessage =>

{

var textRequestMessage = requestMessage as RequestMessageText;

if (textRequestMessage != null && textRequestMessage.Content == "容错")

{

returnfalse;

}

returntrue;

};

}

publicoverride IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)

{

var responseMessage = base.CreateResponseMessage<ResponseMessageText>(); //ResponseMessageText也可以是News等其他类型

responseMessage.Content = "这条消息来自DefaultResponseMessage。";

return responseMessage;

}

}

}

三、新建自动回复接口

WeiXinService构造函数里注入IHttpContextAccessor

public WeiXinService(IHttpContextAccessor​ httpContextAccessor)

{

this._httpContextAccessor = httpContextAccessor;

}

WeiXinService里新建一个回复接口,并发布到云服务器,通过附加到进程调试

[HttpPost("/wx")]

publicasync Task<ContentResult> Receive([FromQuery] PostModel postModel)

{

ContentResult content = new ContentResult();

Console.WriteLine("收到消息");

//测试时候忽略验证

//if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))

//{

// content.Content = "参数错误!";

// return content;

//}

postModel.Token = Token;

postModel.EncodingAESKey = EncodingAESKey;//根据自己后台的设置保持一致

postModel.AppId = AppId;//根据自己后台的设置保持一致

//v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制(实际最大限制 99999)

//注意:如果使用分布式缓存,不建议此值设置过大,如果需要储存历史信息,请使用数据库储存

//自定义MessageHandler,对微信请求的详细判断操作都在这里面。try

{

var maxRecordCount = 10;

var messageHandler = new CustomMessageHandler(_httpContextAccessor.HttpContext.Request.Body, postModel, maxRecordCount);

messageHandler.SaveRequestMessageLog();//记录 Request 日志(可选)var ct = new CancellationToken();

await messageHandler.ExecuteAsync(ct);//执行微信处理过程(关键)

messageHandler.SaveResponseMessageLog();//记录 Response 日志(可选)var result = messageHandler.ResponseDocument.ToString();

content.Content = result;

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

content.Content = "";

}

return content;

}

四、通过接口调试工具测试接口

通过消息调试接口,发送一条文本消息试试

这时候我们发现报错了

百度了下这个错误,发现我复制胜派demo里的代码没有复制全,只需要在ConfigureServices里加入这段代码即可

//如果部署在linux系统上,需要加上下面的配置:

services.Configure<KestrelServerOptions>(options => options.AllowSynchronousIO = true);

//如果部署在IIS上,需要加上下面的配置:

//services.Configure<IISServerOptions>(options => options.AllowSynchronousIO = true);

重新请求接口,发现成功返回xml格式的字符串

用真机测试一下,没毛病

五、本章Gitee地址

https://gitee.com/huguodong520/weixinapi/tree/%E6%8E%A5%E5%85%A5%E5%85%AC%E4%BC%97%E5%8F%B7/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用Furion+sqlsugar实现单用户登录的步骤: 1. 创建一个Furion项目,并添加sqlsugarsqlsugar.extensions库的引用。 2. 在appsettings.json文件中添加数据库连接字符串配置,例如: ``` { "ConnectionStrings": { "DefaultConnection": "Server=localhost;Database=TestDb;Uid=root;Pwd=123456;" } } ``` 3. 创建一个User表,用于存储用户信息,例如: ``` CREATE TABLE `User` ( `Id` bigint(20) NOT NULL AUTO_INCREMENT, `UserName` varchar(50) NOT NULL, `Password` varchar(50) NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` 4. 在Startup.cs文件的ConfigureServices方法中添加sqlsugar的配置,例如: ``` services.AddSqlSugar(new ConnectionConfig() { ConnectionString = Configuration.GetConnectionString("DefaultConnection"), DbType = DbType.MySql, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute }); ``` 5. 在UserService.cs文件中定义一个用于验证用户登录的方法,例如: ``` public class UserService : IUserService { private readonly ISqlSugarClient _sqlSugarClient; public UserService(ISqlSugarClient sqlSugarClient) { _sqlSugarClient = sqlSugarClient; } public async Task<bool> ValidateUserAsync(string userName, string password) { var user = await _sqlSugarClient.Queryable<User>().Where(u => u.UserName == userName && u.Password == password).FirstAsync(); return user != null; } } ``` 6. 在AccountController.cs文件中定义一个用于处理用户登录的方法,例如: ``` public class AccountController : ApiControllerBase { private readonly IUserService _userService; public AccountController(IUserService userService) { _userService = userService; } [HttpPost] public async Task<ActionResult> LoginAsync(LoginInputDto input) { if (await _userService.ValidateUserAsync(input.UserName, input.Password)) { var identity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, input.UserName), }, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); return Ok(new { message = "登录成功!" }); } else { return BadRequest("用户名或密码错误!"); } } [HttpGet] public async Task<ActionResult> LogoutAsync() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Ok(new { message = "退出登录成功!" }); } } ``` 7. 在Configure方法中添加Cookie身份验证中间件的配置,例如: ``` app.UseAuthentication(); app.UseAuthorization(); ``` 8. 在appsettings.json文件中添加身份验证配置,例如: ``` { "Authentication": { "Cookie": { "LoginPath": "/Account/Login", "LogoutPath": "/Account/Logout", "AccessDeniedPath": "/Home/AccessDenied", "Expiration": "1.00:00:00", "SlidingExpiration": true } } } ``` 9. 编写前端页面,使用ajax请求登录接口,登录成功后跳转到主页面。 以上就是使用Furion+sqlsugar实现单用户登录的全部步骤,希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值