How to send form with attachment to DIXA in C#

What you will learn

In this post, I am gonna share a piece of code allowing to send a message to the DIXA webform endpoint via C# programmatically.

By the end of this article, you will learn how to trigger a conversation in DIXA directly from the .NET backend code.

Before we go further, please make sure you've read the official documentation here:

https://support.dixa.help/en/articles/175

You will find there some useful resources regarding: 

  • Creating webform endpoint
  • Creating a conversation thread in different technologies
  • Response examples

With generated endpoint like:

"https://forms.dixa.io/v2/forms/4F1RTIAyJlgzAlFPhahC11/2agyV5bFrEgihjBFsaRX22" and some basic C# skills - you are ready to bake 🥧 some code and start talking to DIXA!

In the example below, we will send the data from the contact form (with an attachment) including some common fields (name, email, subject, message).

Action plan

To send a request to DIXA programmatically, we need to take the following steps:

  • Prepare HttpClient to make a POST request asynchronously
  • Create & fill MultipartFormDataContent with common fields (name, email, subject, message)
  • Add file attachment
  • Send a POST request to the DIXA webform endpoint
  • Deserialize JSON response
  • Verify if the message was delivered and the conversation was created

Common errors:

While trying to send a request to DIXA, you can get a few common errors:

Got statuscode 'UnsupportedMediaType' from remote server
multipart/form-data

The request content was malformed:
Content-Type with a multipart media type must have a 'boundary' parameter

Setting the proper content type before sending the request is a critical part here.

As official docs say:

"ensure that you are using multipart/form-data type of form"

Code sample

using (var client = new HttpClient())
{
   using (var multipartFormDataContent = new MultipartFormDataContent())
   {
      var values = new[]
      {
         new KeyValuePair<string, string>("name", name),
         new KeyValuePair<string, string>("email", email),
         new KeyValuePair<string, string>("subject", subject),
         new KeyValuePair<string, string>("message", messsage)
      };

      foreach (var keyValuePair in values)
      {
         multipartFormDataContent.Add(
            new StringContent(keyValuePair.Value),
            $"\"{keyValuePair.Key}\"");
      }

      if (!string.IsNullOrWhiteSpace(filePath))
      {
         multipartFormDataContent.Add(
            new ByteArrayContent(File.ReadAllBytes(filePath)),
            "attachments",
            Path.GetFileName(filePath));
      }

      var requestUri = "https://forms.dixa.io/v2/forms/4F1RTIAyJlgzAlFPhahC11/2agyV5bFrEgihjBFsaRX22";
      var response = await client.PostAsync(requestUri, multipartFormDataContent);

      if (response.IsSuccessStatusCode)
      {
         var jsonContent = await response.Content.ReadAsStringAsync();

         var result = JsonHelper.DeSerialize<DixaFormResponse>(jsonContent);

         if (!string.IsNullOrWhiteSpace(result.Csid))
         {
            message = "Form was send successfully";
            isOk = true;
         }
      }
   }
}

Expected response

After a successful request to DIXA, we are expecting a JSON object response with one string field called csid (conversation id).

{
    "csid": 1234
}

It's good to create a class to deserialize the JSON response to keep the code nice and clean.

I am not going into deserialization that much - you can use a few popular libraries like Newtonsoft.Json to easily convert JSON string to a strongly typed object. 

public class DixaFormResponse
{
   [JsonProperty("csid")]
   public string Csid { get; set; }
}

Full sample method

public async Task<(bool isOk, string message)> SendFormToDixaEndpoint(
         string name,
         string email,
         string subject,
         string messsage,
         string filePath)
{
   string message = string.Empty;
   bool isOk = false;

   try
   {
      using (var client = new HttpClient())
      {
         using (var multipartFormDataContent = new MultipartFormDataContent())
         {
            var values = new[]
            {
               new KeyValuePair<string, string>("name", name),
               new KeyValuePair<string, string>("email", email),
               new KeyValuePair<string, string>("subject", subject),
               new KeyValuePair<string, string>("message", messsage)
            };

            foreach (var keyValuePair in values)
            {
               multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
                  $"\"{keyValuePair.Key}\"");
            }

            if (!string.IsNullOrWhiteSpace(filePath))
            {
               multipartFormDataContent.Add(new ByteArrayContent(File.ReadAllBytes(filePath)),
                  "attachments",
                  Path.GetFileName(filePath));
            }

            var requestUri = "https://forms.dixa.io/v2/forms/4F1RTIAyJlgzAlFPhahC11/2agyV5bFrEgihjBFsaRX22";
            var response = await client.PostAsync(requestUri, multipartFormDataContent);

            if (response.IsSuccessStatusCode)
            {
               var jsonContent = await response.Content.ReadAsStringAsync();

               var result = JsonHelper.DeSerialize<DixaFormResponse>(jsonContent);

               if (!string.IsNullOrWhiteSpace(result.Csid))
               {
                  message = "Form was send successfully";
                  isOk = true;
               }
            }
         }
      }
   }
   catch (Exception ex)
   {
      message = "Form was not send";
      isOk = false;

      logger.Error(message, ex);
   }

   return (isOk: isOk, message: message);
}

Final words

Integration with DIXA can be done very easily and it gives a lot of possibilities.

I hope you find this short post useful and you can adapt it to your needs.

References:

 

Comments
Leave a Comment