保存至数据库前处理实体CCRecipients字段失效问题排查
CCRecipients字段存储空白值的问题原因
问题描述
在创建Request实体并保存到数据库前,需要对CCRecipients字段的邮箱进行处理:按空格、逗号、分号拆分后,用分号重新拼接,但实际数据库中该字段仅存储空白值,而非预期的格式化邮箱内容。
代码片段
public async Task<IActionResult> OnPost(Models.Requests.Request newRequest) { newRequest.RequestStatusID = (int)RequestStatusEnum.Requested; newRequest.CreatedBy = User.Identity.Name; newRequest.CreatedDate = DateTime.Now; newRequest.LastRequestDate = DateTime.Now; if (!String.IsNullOrEmpty(newRequest.CCRecipients)) { string[] emailSeparators; string ccRecipients = ""; emailSeparators = newRequest.CCRecipients.Split(new Char[] { ' ', ',', ';' }); foreach (var email in emailSeparators) { //ccRecipients.Concat(email + "; "); // I have tried two different ways to concatenate the string ccRecipients = email.Trim() + "; "; } // This is where I'm trying to manipulate the string into the field // To my understanding this is possible but I could be wrong newRequest.CCRecipients = ccRecipients; } await _changeControlContext.AddAsync(newRequest); await _changeControlContext.SaveChangesAsync(); // Other code that is being done return new RedirectToPageResult("RedirectsToAnotherPage"); }
问题原因
字符串拼接逻辑错误
在foreach循环中,你使用ccRecipients = email.Trim() + "; ";的赋值方式,这会直接覆盖掉之前循环积累的所有内容,最终ccRecipients只会保留最后一个处理后的元素值。如果拆分后的最后一个元素是空字符串(比如原字符串以分隔符结尾),最终ccRecipients会变成"; ";当所有拆分元素都是空时,就会生成空白值。Split方法未过滤空元素
默认的Split方法会保留拆分过程中产生的空字符串(比如原字符串包含连续分隔符、开头或结尾是分隔符的场景)。这些空元素会进入循环,当循环到最后一个空元素时,会将之前积累的有效邮箱内容覆盖为空字符串加"; ",最终导致CCRecipients字段被设置为无意义的分隔符组合,甚至空白。
内容的提问来源于stack exchange,提问作者DonDavid12
相关产品推荐
相关产品推荐

