3

I'm trying to receive a POST on an ApiController in ASP.NET Web API and add it to an Azure Queue. The problem I'm having is that I don't want todo parameter binding to a class's properties at this point but rather queue up the JSON as a string in the Azure Queue so that I can get a worker role to deal with it in it's own time.

I'm using Fiddler to do the POST which looks like this:

User-Agent: Fiddler
Host: localhost:50348
Content-Type: application/json
Content-Length: 34

With this request body:

{"text":"pineapple","user":"fred"}

And here's my controller (simplified a little for clarity):

public class MessagesController : ApiController
{   
    // POST api/messages
    public void Post([FromBody] Message message)
    {
        var storage = CloudStorageAccount.DevelopmentStorageAccount;
        var queueClient = storage.CreateCloudQueueClient();
        var queue = queueClient.GetQueueReference("messages");
        if (queue.CreateIfNotExists())
        {
            Trace.WriteLine("Hello world for the first time");
        }

        var msg = new CloudQueueMessage(message.text);
        queue.AddMessage(msg);
    }

This is working with a Message class, which looks like this:

public class Message
{
    public string user { get; set; }
    public string text { get; set; }   
}

This all works fine but I just want to grab the request body (i.e. the JSON) and not bind it but instead add the whole thing into the Azure Queue as a string.

Any ideas? Am I missing something or is my approach just wrong?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Neil Billingham
  • 2,235
  • 4
  • 23
  • 34

2 Answers2

4

You could simply serialize your object using Json.Net by doing something like:

var serializedData = JsonConvert.SerializeObject(message);
var msg = new CloudQueueMessage(serializedData);
queue.AddMessage(msg);
Gaurav Mantri
  • 128,066
  • 12
  • 206
  • 241
  • this works, although it seems odd that I need to parameter bind at all and then have to serialise that object with a third party library. Kinda feels like I'm missing something for something that seems (to me at least) like a pretty normal pattern. I'll wait to see if any more answers come forward and then feedback :) – Neil Billingham Jun 03 '15 at 08:48
  • 2
    Json.Net is one way to serialize the object. You can make use of .net serializer to serialize the object as well. HTH. – Gaurav Mantri Jun 03 '15 at 11:44
  • I guess @Mahesh Jasti has a good point. Having the JSON parameter bind would validate the JSON structure somewhat :) I think I'll go with this solution :) – Neil Billingham Jun 03 '15 at 13:51
1

If it is always a string input then you can try - ([FromBody] string value)

But having an object and then serializing it to string makes sure that the structure of json as string is valid and will avoid having some invalid json data.

Mahesh Jasti
  • 572
  • 3
  • 18