Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Respond with both body and status code in Nancy

Tags:

nancy

I'm new to Nancy and I want to return both a custom HttpStatusCode and a body (content). If I return an HttpStatusCode, it returns it with a blank body. If I return a string then it returns that as the body but always with a 200 status code of OK.

public class SendSMS : NancyModule
{
    public SendSMS()
    {
        Post["/SendSMS"] = parameters =>
            {
                return HttpStatusCode.BadRequest; // this works, no body
                return "Missing \"to\" parameter"; // this works, 200 status code
                // want to return status code with message
            };
    }
}
like image 684
Sachman Bhatti Avatar asked Jan 13 '14 19:01

Sachman Bhatti


3 Answers

You could always create an instance of the Response type and set the Body and StatusCode yourself. If you wanted to take a shortcut you could do something like

var r = (Response)"Some string that goes into the body";
r.StatusCode = 123;

return r;
like image 196
TheCodeJunkie Avatar answered Sep 30 '22 13:09

TheCodeJunkie


This should work.

public class SendSMS : NancyModule
{
   public SendSMS()
   {
       Post["/SendSMS"] = parameters =>
       {
           return Negotiate.WithModel("Missing \"to\" param")
                           .WithStatusCode(HttpStatusCode.BadRequest)           
       };
   }
} 

For more information check the docs on controlling content negotiation.

like image 23
Christian Horsdal Avatar answered Sep 30 '22 12:09

Christian Horsdal


This is the simplest way I've found:

Return from your Module:

return new Response {
                StatusCode = HttpStatusCode.NotFound, ReasonPhrase = "Resource not found"
            };
like image 24
leojh Avatar answered Sep 30 '22 12:09

leojh