Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting JSON to an Azure Queue via an ApiController

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?

like image 769
Neil Billingham Avatar asked Oct 19 '25 10:10

Neil Billingham


2 Answers

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);
like image 165
Gaurav Mantri Avatar answered Oct 22 '25 00:10

Gaurav Mantri


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.

like image 43
Mahesh Jasti Avatar answered Oct 21 '25 23:10

Mahesh Jasti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!