【发布时间】:2016-03-03 08:15:26
【问题描述】:
我的 wpf 应用程序中有一个自托管的 REST API,使用 NancyFX 构建。该应用程序用于在通过 USB 电缆连接到计算机的不同消费产品上更新固件和运行诊断程序。
产品必须连接到计算机才能使用 API。因此,我认为在 WindsorNancyBootstrapper 中覆盖的 RequestStartup() 方法中进行此检查会很聪明,这意味着检查可以在一个位置完成,而不是在每个模块中完成。它按预期工作。如果产品未连接,则没有模块将处理该请求。
但这会在以下情况下导致不必要的副作用:
- 产品未连接到计算机
- 路径无效
这将始终返回 404 并显示设备未连接的消息,而不是“错误 url”消息。我可以将支票移动到每个模块,但我讨厌这样做。我想要什么:
- 如果url无效,不管有没有连接的设备,总是返回404“Bad url”响应,不涉及任何模块
- 如果url有效,但没有连接设备,则返回400“未连接设备”,不涉及任何模块
我想在一个地方做这件事。我四处寻找解决方案,但没有找到任何东西。我在想,也许我的方法是死胡同。毕竟,我使用的是 BeforeRequest 管道,这可能意味着还没有办法验证 URL?
目前我的方法(简化)如下所示:
protected override void RequestStartup(IWindsorContainer container, IPipelines pipelines, NancyContext context)
{
pipelines.BeforeRequest.AddItemToEndOfPipeline(ctx =>
{
// TODO: Here I would like to check if the url is valid in order to be able to return a 404 "bad url" response
if (!_hasConnectedDevice)
{
// ResponseBase is my base class for all my JSON responses
var response = new ResponseBase(ctx.Request.Url, Messages.DeviceNotConnected);
return new JsonResponse(response, new DefaultJsonSerializer())
{
StatusCode = HttpStatusCode.NotFound
};
}
if (!_deviceIsReady)
{
var response = new ResponseBase(ctx.Request.Url, Messages.DeviceNotReady);
return new JsonResponse(response, new DefaultJsonSerializer())
{
StatusCode = HttpStatusCode.BadRequest
};
}
return null;
});
// Catch all unhandled exceptions here.
pipelines.OnError += (ctx, ex) =>
{
var response = new ResponseBase(ctx.Request.Url, ex.Message);
return new JsonResponse(response, new DefaultJsonSerializer())
{
StatusCode = HttpStatusCode.InternalServerError
};
};
}
【问题讨论】:
标签: c# .net rest nancy self-hosting