Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In NancyFx how can I change return status code and set the response text? [duplicate]

Tags:

c#

nancy

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?

like image 680
Daniel James Bryars Avatar asked Dec 30 '14 08:12

Daniel James Bryars


1 Answers

Looks like you should implement a IStatusCodeHandler interface.

According the documentation, I found some articles on this:

  • Custom Error Pages in NancyFx
  • Custom error pages in Nancyfx (C# Web Framework)
  • Nancy and custom error pages (VB.NET code)

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"
            };
        };
    }
}
like image 59
VMAtm Avatar answered Sep 28 '22 12:09

VMAtm