2013-08-25 66 views
3

我为NancyFX做了自定义404处理程序,它工作正常,但有问题。问题在于它甚至会覆盖那些我想发送404代码但是使用我的自定义消息的请求,例如“用户未找到”。NancyFX - 自定义404处理程序覆盖每404响应

处理器

public class NotFoundHandler : IStatusCodeHandler 
{ 
    public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context) 
    { 
     if (statusCode == HttpStatusCode.NotFound) 
     { 
      // How to check here if the url actually exists? 
      // I don't want every 404 request to be the same 
      // I want to send custom 404 with Response.AsJson(object, HttpStatusCode.NotFound) 
      return true; 
     } 

     return false; 
    } 

    public void Handle(HttpStatusCode statusCode, NancyContext context) 
    { 
     context.Response = new TextResponse(JsonConvert.SerializeObject(new { Message = "Resource not found" }, Formatting.Indented)) 
     { 
      StatusCode = statusCode, 
      ContentType = "application/json" 
     }; 
    } 
} 

问题

Get["/"] = _ => 
{ 
    // This will not show "User not found", instead it will be overriden and it will show "Resource not found" 
    return Response.AsJson(new { Message = "User not found" }, HttpStatusCode.NotFound); 
}; 

回答

2

你决定要在IStatusCodeHandler实现(一个或多个)来处理该响应。现在你只是检查状态码本身,而不添加上下文。你可以(例如)做的是只覆盖context.Response如果它不包含符合一定条件的响应,如被类型JsonResponse

if(!(context.Response Is JsonResponse)) 
    { 
      context.Response = new TextResponse(JsonConvert.SerializeObject(new { Message = "Resource not found" }, Formatting.Indented)) 
      { 
       StatusCode = statusCode, 
       ContentType = "application/json" 
      }; 
    } 

既然你有机会获得全NancyContext的,您还可以访问整个RequestResponse(由请求管道中的路由或其他内容返回)。此外,如果您需要更多控制权,您可以在NancyContext.Items中插入任意元数据。

希望这会有所帮助