在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();
}
posted @   ssz0312  阅读(61)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示