NancyFx / Nancy

Lightweight, low-ceremony, framework for building HTTP based services on .Net and Mono
http://nancyfx.org
MIT License
7.15k stars 1.47k forks source link

ApplicationStartup Request.AsString Problem #2941

Closed Nuluvius closed 5 years ago

Nuluvius commented 5 years ago

Description

If a POST request is sent with a body and a parameter then when deserializing Request.Body to string via .AsString() the POST data is correct but the parameter appears in the data and with the value 'null'.

For example, a JSON object would then have an extra field and this would be the parameter but with a null value.

Steps to Reproduce

Define a simple module and add an implementation of IApplicationStartup where pipelines.BeforeRequest.AddItemToStartOfPipeline has an implementation that desearilizes the Request.Body as a string.

For example (hand typed - not tested):

    public class SomeModule : NancyModule
    {
        public RestServiceApi() : base("v1")
        {
            Post["SomeCommand"] = _ =>
            {
                var request = this.Bind<SomeCommandRequest>();
                return Response.AsJson(new SomeCommandResponse {Status = "Unavailable"});
            };
        }
    }
    public class BeforeAllRequests : IApplicationStartup
    {
        public void Initialize(IPipelines pipelines)
        {
            pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx =>
            {
                if (ctx.Request.Body.Length <= 0)
                {
                    return ctx.Response;
                }
                var test = ctx.Request.Body.AsString(); <--- Partial parameter
                return ctx.Response;
            });
        }
    }
   public void WhenSomeCommandCalledWithAParameterTheResponseContainsUnavailable()
    {
        var response = _testContext.Browser.Post("v1/SomeCommand", with =>
        {
            with.HttpRequest();
            with.Query("SomeParameter", "123456789009876");
            with.JsonBody(new SomeCommandRequest
            {
                 SomeField = 111,
                 SomeOtherField = "TEST"
            });
        });

        Assert.That(response.Body.DeserializeJson<SomeCommandResponse>().Status, Is.EqualTo("Unavailable"));
    }

Result: {"someField":"111","someOtherField":"TEST","SomeParameter":null}

Nuluvius commented 5 years ago

Please close this, it looks like it was something in my environment that was causing the issue.