Created
May 17, 2013 12:06
-
-
Save puryfury/5598632 to your computer and use it in GitHub Desktop.
Nancy.ErrorHandling.IStatusCodeHandler implementation example
(Rendering as Razor View error page)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.IO; | |
| using System.Reflection; | |
| using System.Text; | |
| using System.Web; | |
| using CustomerWanso.Defined; | |
| using CustomerWanso.Secutiry; | |
| using Nancy; | |
| using Nancy.Extensions; | |
| using Nancy.Bootstrappers.Ninject; | |
| using Nancy.ViewEngines; | |
| using Nancy.ErrorHandling; | |
| namespace CustomerWanso | |
| { | |
| /// <summary> | |
| /// 404 및 500 오류 페이지 등을 표시하기 위한 상태 처리기 구현 | |
| /// </summary> | |
| public class PageStatusHandler : IStatusCodeHandler | |
| { | |
| private readonly IViewFactory factory; | |
| private readonly IDictionary<HttpStatusCode, string> errorpages = new Dictionary<HttpStatusCode, string> | |
| { | |
| { HttpStatusCode.NotFound, "404.cshtml" }, | |
| { HttpStatusCode.InternalServerError, "500.cshtml" }, | |
| }; | |
| public PageStatusHandler(IViewFactory factory) | |
| { | |
| this.factory = factory; | |
| } | |
| public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context) | |
| { | |
| return this.errorpages.Keys.Any(s => s == statusCode); | |
| } | |
| public void Handle(HttpStatusCode statusCode, NancyContext context) | |
| { | |
| if (context.Response != null && context.Response.Contents != null && !ReferenceEquals(context.Response.Contents, Response.NoBody)) | |
| { | |
| return; | |
| } | |
| string errorPage; | |
| if (!this.errorpages.TryGetValue(statusCode, out errorPage)) | |
| { | |
| return; | |
| } | |
| if (string.IsNullOrEmpty(errorPage)) | |
| { | |
| return; | |
| } | |
| ModifyResponse(statusCode, context, errorPage); | |
| } | |
| private void ModifyResponse(HttpStatusCode statusCode, NancyContext context, string errorPage) | |
| { | |
| var response = factory.RenderView("Views/Error/" + errorPage, new { Exception = context.GetExceptionDetails(), StatusCode = (int)statusCode }, new ViewLocationContext { Context = context }); | |
| response.StatusCode = statusCode; | |
| context.Response = response; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment