Reputation: 2295
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?
Upvotes: 4
Views: 3988
Reputation: 572
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.
Upvotes: 1
Reputation: 136369
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);
Upvotes: 4