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

我们两清 提交于 2019-12-03 22:23:45

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>();

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

Joseph Philbert

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));

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
}

Ideally getting your post data could be accomplished with a simple Bind() call. However, I've seen inconsistent results when using a Bind in a post call such that I've resorted to using the scheme outlined above.

I've seen various discussions about Nancy Bind() working and not working... I've seen both with Post but cannot explain the inconsistency. Where I saw it function properly was where I could guarantee the body of the request was managed as follows:

        var data = Encoding.ASCII.GetBytes (postData);

        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = data.Length;

        using (var stream = request.GetRequestStream ()) {
            stream.Write (data, 0, data.Length);
        }

However, when sending data that should have been similarly handled (though I couldn't confirm) through WSO2 infrastructure (data serialized as a JSON event dictionary sent to a service proxy), Bind failed while the method above succeeded.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!