一、企业微信入参
企业微信配置 机器人助手 : https://work.weixin.qq.com/api/doc/90000/90136/91770
/// <summary> /// 企业微信机器人入参 /// </summary> public class WebHookInput { /// <summary> /// 消息类型,此时固定为text /// </summary> public string msgtype { get { return "text"; } } /// <summary> /// 文本内容 /// </summary> public WebHookTextInput text { get; set; } } public class WebHookTextInput { /// <summary> /// 文本内容,最长不超过2048个字节,必须是utf8编码 /// </summary> public string content { get; set; } }
二、post请求公共方法
public static Toutput PostRequest<Toutput, Tinput>(string url, Tinput input) { Toutput output = default; if (string.IsNullOrEmpty(url)) return output; try { string inputParam = JsonConvert.SerializeObject(input); string result = GetPostUrl(url, inputParam); if (!string.IsNullOrEmpty(result)) { output = JsonConvert.DeserializeObject<Toutput>(result); } } catch (Exception ex) { } return output; } //post private static string GetPostUrl(string url, string postData, Dictionary<string, string> heardsDic = null) { string result = string.Empty; try { HttpWebRequest request = null; if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { request = WebRequest.Create(url) as HttpWebRequest; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request.ProtocolVersion = HttpVersion.Version11; // 这里设置了协议类型。 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; request.KeepAlive = false; ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 100; ServicePointManager.Expect100Continue = false; } else { request = (HttpWebRequest)WebRequest.Create(url); } request.Method = "POST"; //使用get方式发送数据 request.ContentType = "application/json"; request.Referer = null; request.AllowAutoRedirect = true; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; request.Accept = "*/*"; #region 请求头数据 if (heardsDic != null) { foreach (var item in heardsDic) { SetHeaderValue(request.Headers, item.Key, item.Value); } } #endregion 请求头数据 byte[] data = Encoding.UTF8.GetBytes(postData); Stream newStream = request.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); //获取网页响应结果 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); using (StreamReader sr = new StreamReader(stream)) { result = sr.ReadToEnd(); } } catch (Exception ex) { } return result; } private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //总是接受 } private static void SetHeaderValue(WebHeaderCollection header, string name, string value) { var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); if (property != null) { var collection = property.GetValue(header, null) as NameValueCollection; collection[name] = value; } }
三、发送企业微信消息封装
/// <summary> /// 发送企业微信机器人消息 /// </summary> /// <param name="param"></param> public void SendQYApiMessage(WebHookInput param) { var data =PostRequest<dynamic, WebHookInput>(“https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=693axxx6-7aoc-4bc4-97a0-0ec2sifa5aaa”, param); }
四、api接口的统一处理,告警超过1秒钟接口
public class ExterApiFilter : ActionFilterAttribute { private Stopwatch _Stopwatch { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); _Stopwatch = new Stopwatch(); _Stopwatch.Start(); } /// <summary> /// 出接口 /// </summary> /// <param name="filterContext"></param> protected override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); _Stopwatch.Stop(); int totalMill = (int)_Stopwatch.Elapsed.TotalMilliseconds;//接口处理时间:毫秒 string logdata = $"Controller={filterContext.RouteData.Values["Controller"].ToString()},Action={filterContext.RouteData.Values["Action"].ToString()},接口处理时间:{totalMill}毫秒"; #region 企业微信消息通知 //写入发送消息 duration = 10000; if (totalMill > duration) { string contents = $"接口请求响应超一秒," + logdata; SendQYApiMessage(WebHookInput() { text = new WebHookTextInput() { content = contents } }); } #endregion 企业微信消息通知 } }
本文介绍了如何使用C# .NET进行企业微信接口对接,特别是针对接口请求时长超过1秒的情况,实现了告警功能。详细内容包括企业微信的配置、POST请求公共方法的编写、发送企业微信消息的封装以及API接口的统一处理策略。
653

被折叠的 条评论
为什么被折叠?



