[英]Check if route is valid in RequestStartup in NancyFX
我的WPF應用程序中有一個使用NancyFX構建的自托管REST API。 該應用程序用於更新固件並在通過USB電纜連接到計算機的不同消費類產品上運行診斷。
必須將產品連接到計算機才能使用API。 因此,我認為在WindsorNancyBootstrapper中重寫的RequestStartup()方法中執行此檢查將很明智,這意味着可以在一個位置而不是在每個模塊中進行檢查。 它按預期工作。 如果未連接產品,則沒有模塊將處理該請求。
但這在以下情況下導致了不良的副作用:
這將始終返回404消息,提示設備未連接,而不是“錯誤網址”消息。 我可以將檢查移到每個模塊,但是我不願意這樣做。 我想要的是:
我想在一個地方做到這一點。 我到處尋找解決方案,但沒有發現任何東西。 我在想,也許我的方法是死胡同。 畢竟,我使用的是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
};
};
}
我能想到的最好的方法是做與安全性類似的事情,即在INancyModule上創建擴展方法,該擴展方法會在pipline中添加一些內容,以檢查設備是否已插入並准備就緒並返回相關信息。狀態碼,如果不是,則返回null,然后在每個模塊中只想使用添加的USB設備:
this.RequiresUsbThings(); //或任何您想稱呼的:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.