8

Using Nancy I can return a response like this:

public class MainModule : NancyModule
{
    public MainModule()
    {
        Get["/"] = parameters => {
            return "Hello World";
        };
    }
}

And I can return a status 400 like this:

public class MainModule : NancyModule
{
    public MainModule()
    {
        Get["/"] = parameters => {
            return HttpStatusCode.BadRequest;
        };
    }
}

How do I return a specific http status code and set the response text too?

Daniel James Bryars
  • 4,429
  • 3
  • 39
  • 57

1 Answers1

3

Looks like you should implement a IStatusCodeHandler interface.

According the documentation, I found some articles on this:

So your code should be like this:

public class StatusCodeHandler : IStatusCodeHandler  
{  
    private readonly IRootPathProvider _rootPathProvider;  

    public StatusCodeHandler(IRootPathProvider rootPathProvider)  
    {  
        _rootPathProvider = rootPathProvider;  
    }  

    public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)  
    {  
        return statusCode == HttpStatusCode.NotFound;  
    }  

    public void Handle(HttpStatusCode statusCode, NancyContext context)  
    {  
        context.Response.Contents = stream =>  
        {  
            var filename = Path.Combine(_rootPathProvider.GetRootPath(), "content/PageNotFound.html");  
            using (var file = File.OpenRead(filename))  
            {  
                file.CopyTo(stream);  
            }  
        };  
    }  
}

So we can see here:

  1. A constructor for your class with information about your current root
    StatusCodeHandler(IRootPathProvider rootPathProvider)
  2. A methods which decides, are we need to handle current request with this class
    HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
  3. Handle method which adds to the Response contents the custom error file contents from your root directory
    Handle(HttpStatusCode statusCode, NancyContext context)

If for some reason this isn't an option for you, simply create an HttpResponse which needed status and text, like this:

public class MainModule : NancyModule
{
    public MainModule()
    {
        Get["/"] = parameters => {
            return new Response {
                StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = "Hello World"
            };
        };
    }
}
VMAtm
  • 27,943
  • 17
  • 79
  • 125