D. Stewart
D. Stewart

Reputation: 471

C# getting HTTP body using Nancy

quick question. I'm using Nancy to convert REST calls to api calls in a project I'm working on. I can't quite get it to work.

I've got Nancy setup and working, for GET requests it's fine. However when I make a POST request using the built in RestClient, like:

            restClient.Post("/test", "Param");

I can't figure out how to get "Param" out once the call has been made.

I have the NancyModule setup as such:

public class TestNancyModule : NancyModule {
    public TestNancyModule() {
        Post["/test"] = p => {
            for(KeyValuePair<dynamic, dynamic> kvp in (DynamicDictionary)p)
                Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value);
        }
    }
}

I have a breakpoint setup inside the NancyModule, which is getting hit when I make a post request to localhost/test, but I can't for the life of me figure out how to extract "Param" out once I'm inside the Nancy module. Ideally I'd be able to just do something like

    string POSTParameters = p["Value"]
    //POSTParameters now equals "Param"

Any suggestions?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Edit: I'm leaving the original post up, but I'll clarify here. I was meaning to ask how to access the HTTP body of incoming requests. Unfamiliarity with the protocol led to some errors on my part using the wrong terminology.

Upvotes: 2

Views: 4358

Answers (4)

Artem A
Artem A

Reputation: 2438

In new versions of NancyFx (1.4+) you can use this solution:

using Nancy.IO;
...
var yourString = RequestStream.FromStream(Request.Body).AsString();

while

var yourString = Request.Body.AsString(); 

is supported no more.

Upvotes: 3

derek
derek

Reputation: 123

For query params you can use Nancy's Request object on the module.

var queryParam =  this.Request.Query.ParamName;

For an actual post body you can use

this.Bind(); 

Which will create a dynamic with the properties specified in the body.

Upvotes: 0

Phill
Phill

Reputation: 18796

You can use .AsString() on the body if you pull in Nancy.Extensions

var thing = Request.Body.AsString();

This is the Nancy way.

Upvotes: 3

D. Stewart
D. Stewart

Reputation: 471

Figured it out, it's accessible under the "Request" field.

For the code I can get the Body by doing something like

            byte[] response = new byte[Request.Body.Length];
            Request.Body.Read(response, 0, (int)Request.Body.Length);

and

            string POSTParameters = System.Text.Encoding.Default.GetString(response);

which is exactly what I was looking for. If the body were going to be more complicated I wouldn't recommend doing such, but I'm only going to be passing in single words for this post.

Upvotes: 1

Related Questions