Capturing SendGrid Events With ASP.NET WebAPI and Task async

 

Problem

I’ve been using SendGrid’s API WebHooks to capture email events (Version 1).  This version sends one event at a time which has always been a pretty bad idea.  When I first did the integration a year or so ago, the only way to capture multiple events at once was to consume some proprietary non-JSON like protocol.  I declined.  They finally have upgraded the API to send standard JSON records and are going to obsolete version 1 so I need to change.  Here goes…

Send Grid Event Notification Configuration

First, you need to go into Event Notification and change to (v3) of the config.  Then, I pressed the “Test Your Integration” button while running fiddler to grab the JSON SendGrid generates (see screen shot)

image

Figure Out The JSON Structure

The generated JSON looks like this:

image

At this point, there are lots of ways to decode the JSON.  My choice is to us http://json2csharp.com, paste in my json data and it generates the classes I need to encode the JSON data into.

image

Next, I create a WebAPI controller in ASP.NET and simply have with one method for POST.  I add the above classes and then unwind the data when it comes in as follows.

The controller I build (as a guess) looks like this: (I’m leaving out what I do with the data in the foreach.  Reality is I’m going to stuff it in a database)

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Ajax.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace WebAPI.rest
{
    public class SendGridController : ApiController
    {
        public async Task Post()
        {
            string jsonData = await Request.Content.ReadAsStringAsync();
            dynamic dataList = JArray.Parse(jsonData);

            using (
                var sqlConnection =
                    new SqlConnection(ConfigurationManager.ConnectionStrings["CodeCampSV06"].ConnectionString))
            {
                sqlConnection.Open();

                foreach (var rec in dataList)
                {

                    string eventName = (string) rec["event"] ?? "";
                    string email = (string) rec["email"] ?? "";
                    string category = "";
                    //string category = rec.category != null && rec.category.Count > 0 ? rec.category[0] : "";
                    string url =  (string) rec["url"] ?? "";
                    string generalType =  (string) rec["type"] ?? "";
                    string reason =  (string) rec["reason"] ?? "";
                    string statusString = (string) rec["status"] ?? "";
                    string attempt =(string) rec["attempt"] ?? "";
                    string responseString = (string)rec["response"] ?? "";
                    string emailpkid = (string)rec["emailpkid"] ?? "";

                     // do something with the data!
                    
                }
            }
        }
    }
}

 

Testing The WebAPI Rest Controller

To test the controller, I need to simulate a call that SendGrid will be issuing to me.  I do that by using fiddler to compose a new query.  Below is a screen shot of what that composed query looks like on my system.  Notice I’ve set it to POST and I’ve pasted in the content JSON that SendGrid will be sending me (got it from the test post above)

image

You can now see, when I press “Execute in fiddler” while Visual Studio is running in debug mode, my data is all coming in as I expect.

image

 

That’s it! basically we’ve done it.  HTHs.  We’ve build a WebAPI controller using async to capture data coming in as a JSON payload.

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP for the past 7 years. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. Peter Kellner says:

    To be honest, there is another problem with this code I still need to work out so no, it is not tested. The problem i’ve been having (and would love to hear the solution, I may do a microsoft msdn support call to solve it) is that the headers sent by sendgrid (specifically the json one) is causing webapi to respond with a 404. Once I solve that, I’m guessing I will run into the problem you mention. return a 200 is quite easy though so that should no be too hard. Let me know your progress and I’ll update the post.

  2. Kirk Quinbar says:

    were you able to successfully receive events with this code. the reason I ask is according to the documentation for sendgrid event api, their calling routine is expecting a 200 response from the url, but in my testing with fiddler, it seems like its giving a 204 response which means no content returned. in this case I think sendgrid event api will retry the call and keep retrying it? thoughts or observations in your testing?

Trackbacks

  1. […] Capturing SendGrid Events With ASP.NET WebAPI and Task async (Peter Kellner) […]

Follow

Get every new post delivered to your Inbox

Join other followers: