Guest User

Untitled

a guest
Oct 18th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. namespace Epic.Infrastructure {
  2. using System;
  3. using System.Linq;
  4. using Nancy;
  5. using Nancy.ErrorHandling;
  6. using Nancy.ViewEngines;
  7.  
  8. public class EpicErrorHandler : CustomRazorErrorHandler {
  9. public EpicErrorHandler(IViewFactory factory, IViewLocationCache cache) : base(factory, cache) {}
  10.  
  11. public override bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context) {
  12. return statusCode == HttpStatusCode.NotFound || statusCode == HttpStatusCode.InternalServerError;
  13. }
  14.  
  15. public override void Handle(HttpStatusCode statusCode, NancyContext context) {
  16. switch (statusCode) {
  17. case HttpStatusCode.NotFound:
  18. RenderView(context, "404");
  19. break;
  20. case HttpStatusCode.InternalServerError:
  21. RenderView(context, "500");
  22. break;
  23. }
  24. context.Response.StatusCode = statusCode;
  25. }
  26. }
  27.  
  28. public abstract class CustomRazorErrorHandler : IErrorHandler {
  29. private readonly IViewLocationCache _cache;
  30. private readonly IViewFactory _factory;
  31.  
  32. protected CustomRazorErrorHandler(IViewFactory factory, IViewLocationCache cache) {
  33. _factory = factory;
  34. _cache = cache;
  35. }
  36.  
  37. #region IErrorHandler Members
  38.  
  39. public abstract bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context);
  40. public abstract void Handle(HttpStatusCode statusCode, NancyContext context);
  41.  
  42. #endregion
  43.  
  44. protected void RenderView(NancyContext context, string viewName, dynamic model = null) {
  45. bool foundMatchingView = _cache.Any(x =>
  46. x.Name.Equals(viewName) &&
  47. x.Extension.Equals("cshtml", StringComparison.OrdinalIgnoreCase));
  48.  
  49. if (foundMatchingView) {
  50. var viewContext = new ViewLocationContext {Context = context};
  51.  
  52. context.Response = _factory.RenderView(viewName, model, viewContext);
  53. }
  54. }
  55. }
  56. }
Add Comment
Please, Sign In to add comment