在Asp.Net Core中发送企业微信信息
在Asp.Net Core中发送企业微信信息
起因
将原.net framework通知程序升级到.net core,原先直接用的别人的包(最后更新时间:2015年),百度没找到想要的,于是自己写吧。
实现
企业微信文档链接https://developer.work.weixin.qq.com/document/path/90236#文本卡片消息
在appsettings.json
添加:
"WeiXin": {
"AppId": "填自己的",
"Secret": "填自己的",
"agentid": "填自己的"
},
使用IConfiguration
注入,Configuration["WeiXin:AppId"]
读取
构建相关类:
public class WeiXinDto
{
public string? touser { get; set; }
public string? msgtype { get; set; }
public int? agentid { get; set; }
public object? textcard { get; set; }
}
public class AccessTokenDto
{
public int? errcode { get; set; }
public string? errmsg { get; set; }
public string? access_token { get; set; }
public int? expires_in { get; set; }
}
使用IHttpClientFactory
接口:在program.cs
中添加builder.Services.AddHttpClient();
获取token:
public async Task GetToken()
{
using HttpResponseMessage httpResponse = await client.GetAsync("请求链接");
var result = httpResponse.Content.ReadAsStringAsync().Result;
var responseObject = JsonSerializer.Deserialize<AccessTokenDto>(result);
access_token = responseObject?.access_token;
}
发送信息:
public async Task SendWinXinMsg(string msgtype, string touser,int agentid, string title,string description,string url)
{
WeiXinDto weiXinDto = new WeiXinDto();
weiXinDto.touser = touser;
weiXinDto.agentid = agentid;
weiXinDto.msgtype = msgtype;
weiXinDto.textcard = new
{
title=title,
description=description,
url=url
};
await GetToken();//获取access_token
using StringContent json = new(
JsonSerializer.Serialize(weiXinDto, new JsonSerializerOptions(JsonSerializerDefaults.Web)),
Encoding.UTF8,
MediaTypeNames.Application.Json);
using HttpResponseMessage httpResponse=await client.PostAsync("请求链接", json);
httpResponse.EnsureSuccessStatusCode();
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)