gpt4 book ai didi

c# - NancyFX - 自定义 404 处理程序覆盖每个 404 响应

转载 作者:行者123 更新时间:2023-11-30 17:03:36 27 4
gpt4 key购买 nike

我为 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);
};

最佳答案

您决定要在您的IStatusCodeHandler 实现中处理哪些响应。现在,您只是在检查状态代码本身,而不向其添加上下文。你可以做的(例如)将只覆盖 context.Response 如果它不包含满足特定标准的 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 中。

希望对你有帮助

关于c# - NancyFX - 自定义 404 处理程序覆盖每个 404 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18429715/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com