基于notification.alert值在C#中实现分支邮件发送逻辑
基于Azure HTTP触发器的C#邮件告警分支逻辑实现
需求说明
原代码用于响应Azure HTTP触发器,发送传感器异常警告邮件。现在需要根据notification.alert字段的值(0表示异常开始,1表示告警停止),分别发送对应内容的邮件:
- 当
alert=0时,邮件内容包含“设备已开始上报异常” - 当
alert=1时,邮件内容包含“设备已停止上报异常”
修改后的完整代码
#r "Newtonsoft.Json" #r "SendGrid" using System; using System.Collections.Generic; using SendGrid.Helpers.Mail; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; public static SendGridMessage Run(HttpRequest req, ILogger log) { string requestBody = new StreamReader(req.Body).ReadToEnd(); log.LogInformation(requestBody); var notifications = JsonConvert.DeserializeObject<IList<Notification>>(requestBody); SendGridMessage message = new SendGridMessage(); // 初始化邮件内容 string content = ""; foreach(var notification in notifications) { log.LogInformation($" - time: {notification.time}, value: {notification.value}, lowerbound: {notification.lowerbound}, upperbound: {notification.upperbound}, device: {notification.device}, alert: {notification.alert}"); // 根据alert值分支处理邮件主题和内容 if (notification.alert == 0) { message.Subject = "传感器异常告警:设备开始上报异常"; content += $"设备【{notification.device}】已开始上报异常<br/><br/>"; } else if (notification.alert == 1) { message.Subject = "传感器告警恢复:设备停止上报异常"; content += $"设备【{notification.device}】已停止上报异常<br/><br/>"; } // 添加详细数据表格(可选,保留原代码的表格展示) content += "<table><tr><th>时间</th><th>数值</th><th>下限</th><th>上限</th></tr>"; content += $"<tr><td>{notification.time}</td><td>{notification.value}</td><td>{notification.lowerbound}</td><td>{notification.upperbound}</td></tr>"; content += "</table><hr/>"; } message.AddContent("text/html", content); return message; } public class Notification { public string time { get; set; } public string value { get; set; } public string lowerbound { get; set; } public string upperbound { get; set; } public string device { get; set; } // 新增alert字段,对应传入的0/1值 public int alert { get; set; } }
关键改动说明
- 新增
alert字段:在Notification类中添加public int alert { get; set; },确保能解析请求中的alert参数 - 分支逻辑实现:使用C#的
if-else语句判断notification.alert的值,分别设置不同的邮件主题和内容 - 内容动态生成:根据告警状态拼接对应的提示文本,同时保留原有的数据表格展示(可根据需求调整是否保留)
- 日志增强:在日志中新增
alert字段的输出,方便调试
内容的提问来源于stack exchange,提问作者puradrogasincortar
相关产品推荐
相关产品推荐

