将C#中的电子邮件地址字符串解析为MailAddress对象



我有一个C#后端代码,它从TypeScript中的客户端代码接收POST请求。

JSON是用JSON.stringfy(objectOfData(为POST完成的;

在C#代码中,当我尝试使用这样的对象时,我得到了一个异常:

// Passed into this function is InboundObjectDTO inboundObject
// inboundObject.Email in debugger is like so: ""a@example.com""
var message = new MailMessageDTO
{
Subject = "My Subject",
MailAddresses = new List<MailAddress>()
};
message.MailAddresses.Add(new MailAddress(inboundObject.Email));

我是否应该以某种方式提前反序列化对象?我在对象中有3个字符串:电子邮件、消息和名称。

上面的最后一行代码给了我";MailAddresses异常中的无效字符"我猜它需要以适当的方式删除所有多余的引号。

正如OP最初假设的那样,问题是电子邮件地址周围的引号,我们所需要做的就是删除这些引号。此过程被称为对输入进行消毒

最初的方法很难遵循,发布的异常信息也不明确,该解决方案展示了如何净化输入并返回异常的更多相关信息。

您粘贴的示例"quot;一个@example.com"如果您只是简单地使用消毒步骤的结果,那么在包含sanize逻辑的原始代码中不会失败!

您应该将代码块包装在try-catch中,以便捕获异常并输出失败的特定字符串值:

string email = inboundObject.Email;
MailMessageDTO message = null;
try
{
// sanitized the email, removed known invalid characters
email = email.Replace(""", "");
// construct the payload object
message = new MailMessageDTO
{
Subject = "My Subject",
MailAddresses = new List<MailAddress>()
};
message.MailAddresses.Add(new MailAddress(email));
}
catch (Exception ex)
{
throw new ApplicationException($"Failed to construct MailMessage for email: {email}", ex);
}

现在,当这失败时,我们在异常内部有更多的信息要处理,事实上,这种情况本身可能保证了它自己的独立可重用方法:

public MailAddress SanitizeEmail(string emailAddress)
{
string email = emailAddress;
try
{
// sanitized the email, removed known invalid characters
email = email.Replace(""", "");

// TODO: add other rules an replacement cases as you find them
return new MailAddress(email);
}
catch (Exception ex)
{
throw new ApplicationException($"Failed to sanitize email address: '{email}' [original input: '{emailAddress ?? "NULL" }']", ex);
}
}

你可以用来称呼它

message.MailAddresses.Add(SanitizeEmail(email));

更新

OP的原始代码包括已发布代码中不再存在的参考和测试条件,此响应仅进行了少量更新,以反映中的这些变化

如果您将json数据发布到控制器操作,您可以使用[FromBody][FromBody]将从请求体中获取值:

public IActionResult Index([FromBody]inboundObject inboundObject)
{
...
}

或者您可以使用JsonConvert.DeserializeObject来反序列化要指定的JSON。NET类型:

message.MailAddresses.Add(new MailAddress(JsonConvert.DeserializeObject<string>(inboundObject.Email)));

最新更新