Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nancy (C#): How do I get my post data?

I'm using Corona SDK to post data to my C# server:

headers["Content-Type"] = "application/x-www-form-urlencoded"
headers["Accept-Language"] = "en-US"

local body = "color=red&size=small"

local params = {}
params.headers = headers
params.body = body

network.request( host .. "/UpdateHand", "POST", nwListener, params )

I receive a message on the server:

  Post["/UpdateHand"] = x =>
        {
            Console.WriteLine("Received ...");
            return "Ok";
        };

But when I check the data (when I put a breakpoint on it) I don't see where my data is locaded (i.e. the params.body or params.headers). How can I extract this information?

I should POST it correctly according to the documentation on Corona: http://docs.coronalabs.com/daily/api/library/network/request.html

like image 290
Westerlund.io Avatar asked Jul 26 '14 10:07

Westerlund.io


4 Answers

The post data is in

this.Request.Body

If you have suitable type you can deserialize your data to it using model binding:

var x = this.Bind<YourType>();
like image 101
Christian Horsdal Avatar answered Oct 23 '22 19:10

Christian Horsdal


There is a Nancy extension for this. You will need to include the namespace for it.

using Nancy.Extensions;
var text =  Context.Request.Body.AsString();

I like how concise this is, part of Nancy's super-duper easy path.

But a word of caution! This method leaves the stream at the end, so subsequent calls will return empty string. To fix this, always reset the stream immediately afterwards, like so:

Request.Body.Seek(0, SeekOrigin.Begin);

Nancy 2.0 is supposed to correct this so that the stream position is reset by default.

https://github.com/NancyFx/Nancy/pull/2158

like image 42
Daniel Williams Avatar answered Oct 23 '22 20:10

Daniel Williams


This actually works great:

var body = this.Request.Body; 
int length = (int) body.Length; // this is a dynamic variable
byte[] data = new byte[length]; 
body.Read(data, 0, length);             
Console.WriteLine(System.Text.Encoding.Default.GetString(data));
like image 8
Joseph Philbert Avatar answered Oct 23 '22 21:10

Joseph Philbert


For Nancy 2.0.0, Request.Body is a Stream rather than a RequestStream, so doesn't have an AsString method. However, this seems to work:

using (var reqStream = RequestStream.FromStream(Request.Body))
{
    var body = reqStream.AsString();
    // ... do stuff with body
}
like image 3
Paul Stephenson Avatar answered Oct 23 '22 19:10

Paul Stephenson