SendGrid dynamic template contains empty data - .NET Core

Viewed 998

I am trying to send an email with a specific dynamic template and data. Email is successfully sent but contains empty data. The handle method is part of Azure Function. Recently I've changed Newtonsoft JSON to System.Text.Json and maybe this causes some problems.

Email: enter image description here

SendGrid dynamic template configuration: enter image description here

C# Code:

        public async Task Handle(SendEmailCommand command)
        {
            var client = new SendGridClient(emailConfig.SendGridApiKey);
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress(emailConfig.Sender));
            msg.AddTo(new EmailAddress(command.To));
            msg.SetTemplateId(command.SendGridTemplateId);

            if (command.SendGridDynamicTemplateData != null)
            {
                var templateData = new TemplateData();

                command.SendGridDynamicTemplateData.TryGetValue("topic", out var topic);
                command.SendGridDynamicTemplateData.TryGetValue("email", out var email);
                command.SendGridDynamicTemplateData.TryGetValue("name", out var name);
                command.SendGridDynamicTemplateData.TryGetValue("message", out var message);

                templateData.Topic = topic.ToString();
                templateData.Email = email.ToString();
                templateData.Name = name.ToString();
                templateData.Message = message.ToString();

                msg.SetTemplateData(templateData);
            }

            await client.SendEmailAsync(msg);
        }

        private class TemplateData
        {
            [JsonPropertyName("topic")]
            public string Topic { get; set; }

            [JsonPropertyName("email")]
            public string Email { get; set; }

            [JsonPropertyName("name")]
            public string Name { get; set; }

            [JsonPropertyName("message")]
            public string Message { get; set; }
        }

Am I doing something wrong?

1 Answers

I noticed the same thing. The [JsonPropertyName] attribute from System.Text.Json doesn't seem to be recognized by the SendGrid API. I had to use the [JsonProperty] attribute from Newtonsoft.Json in order to get the parameters to appear on the email.

Related