In NancyFx, how can I change the return status code and set the response text?

Using Nancy, I can return an answer like this:

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

And I can return status 400 as follows:

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

How can I return a specific http status code and set a response text?

+6
source share
1 answer

It looks like you should implement the IStatusCodeHandler interface. I will tell you the details soon.

According to the documentation , I found several articles about this:

So your code should look 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:

  • Constructor for your class with information about your current root
    StatusCodeHandler(IRootPathProvider rootPathProvider)
  • Methods that decide whether to handle the current request using this class
    HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
  • A descriptor method that adds the contents of the user error content from your root directory to the Response content
    Handle(HttpStatusCode statusCode, NancyContext context)

If for some reason this is not an option for you, just create an HttpResponse that needs status and text, for example:

 public class MainModule : NancyModule { public MainModule() { Get["/"] = parameters => { return new Response { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = "Hello World" }; }; } } 
+1
source

Source: https://habr.com/ru/post/980292/


All Articles