简体   繁体   English

将 C# 中的 email 地址字符串解析为 MailAddress object

[英]Parse an email address string in C# to MailAddress object

I have a C# backend code that receives a POST request from the client side code in TypeScript.我有一个 C# 后端代码,它从 TypeScript 中的客户端代码接收 POST 请求。

The JSON is done for the POST with JSON.stringify(objectOfData); JSON 为 POST 完成 JSON.stringify(objectOfData);

In the C# code I am getting an exception when I try to use the object like so:在 C# 代码中,当我尝试像这样使用 object 时出现异常:

// 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));

Am I supposed to deserialize the object somehow before hand?我应该事先以某种方式反序列化 object 吗? I have 3 strings in the object: email, message, and name.我在 object 中有 3 个字符串:email、消息和名称。

The last line of code above gives me "An invalid character in MailAddresses exception."上面的最后一行代码给了我“MailAddresses 异常中的无效字符”。 I am guessing it needs to have all the extra quotes and such removed in a proper way.我猜它需要以适当的方式删除所有额外的引号。

As OP had originally postulated, the issue is the quotes around the email address, all we need to do is remove those quotes.正如 OP 最初假设的那样,问题在于 email 地址周围的引号,我们需要做的就是删除这些引号。 This process is referred to as Sanitizing the input.此过程称为清理输入。

The original methodology was hard to follow and the exception information posted was ambiguous, this solution shows how to sanitise the input and return more relevant information with the exception.原始方法难以遵循,并且发布的异常信息不明确,此解决方案展示了如何清理输入并返回更多与异常相关的信息。

The example you have pasted ""a@example.com"" would not fail in your original code that included the santize logic, if you had simply used the result of the sanitize step!如果您只是使用了清理步骤的结果,那么您粘贴的示例“a@example.com”在包含清理逻辑的原始代码中不会失败!

You should wrap the code block in a try-catch so you can capture the exception and output the specific string value that has failed:您应该将代码块包装在 try-catch 中,以便您可以捕获异常和 output 失败的特定字符串值:

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);
}

Now when this fails, we have more information to work with inside the exception, infact this situation itself probably warrants it's own separate reusable method:现在,当这失败时,我们有更多信息可以在异常中使用,事实上这种情况本身可能保证它有自己独立的可重用方法:

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);
    }
}

You could call this using:您可以使用以下方法调用它:

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

Update更新

OP's original code included references and test conditions that are no longer in the posted code, this response has only been marginally updated to reflect those changes OP 的原始代码包含已发布代码中不再存在的引用和测试条件,此响应仅进行了少量更新以反映这些更改

If you are posting json data to controller action,you can use [FromBody] , [FromBody] will get values from the request body:如果您将 json 数据发布到 controller 操作,您可以使用[FromBody][FromBody]将从请求正文中获取值:

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

Or you can use JsonConvert.DeserializeObject to deserialize the the JSON to specified .NET type:或者您可以使用JsonConvert.DeserializeObject将 JSON 反序列化为指定的 .NET 类型:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM