using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace ddAlter.Tools { public class dingding { private readonly IHttpClientFactory _httpClientFactory; /// ///调用webhook /// /// ///webhook地址 ///消息 /// public static async Task SendWebhooks(string url, T data) where T : class { JsonConvert.DefaultSettings = new Func(() => new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver() }); var jsonData = JsonConvert.SerializeObject(data); using (var httpClient = new HttpClient()) { var content = new StringContent(jsonData); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = await httpClient.PostAsync(url, content); result.EnsureSuccessStatusCode(); } } /// /// 执行发送消息 /// /// /// public async Task SendDingTalkMessage(string url, object value) { var sendMessage = JsonConvert.SerializeObject(value); var request = new HttpRequestMessage(HttpMethod.Post, url) { //钉钉文档需指定UTF8编码 Content = new StringContent(sendMessage, Encoding.UTF8, "application/json") }; var client = _httpClientFactory.CreateClient(); var response = await client.SendAsync(request); return response; } } }