DanP
DanP

Reputation: 6478

Handling batched sendgrid events using the asp.net web api

I'm attempting to use an asp.net web api application to handle batched SendGrid events and I've run into a stumbling block due to the way SendGrid handles the content type header of the post it sends.

From their documentation:

Batched event POSTs have a content-type header of application/json, and contain exactly one JSON string per line, with each line representing one event. Please note that currently the POST headers define this post as application/json, though it’s not; each line is a valid JSON string, but the overall POST body is not.

So, given a controller:

public class SendGridController : ApiController 
{ 
   // POST api/values 
   public void Post([FromBody]string value) 
   { 
   // do something with value
   }
}

Making a post to it as SendGrid does will result in "value" being null.

string URI = "http://localhost:3018/api/sendgrid/";
string myParameters = 
@"={""email"":""[email protected]"",""timestamp"":1322000095,""user_id"":""6"",""event"":""bounced""}
{""email"":""[email protected]"",""timestamp"":1322000096,""user_id"":""9"",""event"":""bounced""}";


using (var wc = new System.Net.WebClient())
{
    wc.Headers[System.Net.HttpRequestHeader.ContentType] = "application/json"; // I work fine if "application/x-www-form-urlencoded" is used.
    wc.UploadString(URI, myParameters);
}

If I change the content type in my client example to "application/x-www-form-urlencoded", everything works as expected.

Is there an easy way for me to override this convention such that I can handle the badly formed "json" that sendgrid provides as a string in my controller method?

Upvotes: 1

Views: 553

Answers (1)

DanP
DanP

Reputation: 6478

Ok, I finally figured it out. The trick was to remove the "value" param and work with the request object directly.

So something like:

public class SendGridController : ApiController 
{ 
   // POST api/values 
   public void Post() 
   { 
      var value = Request.Content.ReadAsStringAsync().Result;
      // do something with value
   }
}

Upvotes: 1

Related Questions