在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();
}
标签:Asp,string,get,token,set,weiXinDto,public
From: https://www.cnblogs.com/ssz0312/p/18127270