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?
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:
StatusCodeHandler(IRootPathProvider rootPathProvider)
HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
Response
contents the custom error file contents from your root directoryHandle(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"
};
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With