无法对 Nancy 自托管执行简单的 GET 请求:RuntimeBinderException 和 ViewNotFoundException

Cannot perform simple GET request to Nancy self-hosted: RuntimeBinderException and ViewNotFoundException

我的代码:

public class MyWebService : IDisposable
{
    private readonly NancyHost _host;

    public MyWebService(int port = 7017)
    {
        var uri = new Uri(string.Format("http://localhost:{0}", port));
        _host = new NancyHost(uri);
        _host.Start();
    }

    public void Dispose()
    {
        if (_host != null)
        {
            _host.Stop();
            _host.Dispose();
        }
    }
}

internal class MyWebModule : NancyModule
{
    public MyWebModule()
    {
        Get["/"] = _ => "Received GET request";
    }
}

当 运行 遵循 HTTP 请求时:GET http://localhost:7017/ 使用 Insomnia REST client,我得到以下神秘异常:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot convert type 'Nancy.ErrorHandling.DefaultStatusCodeHandler.DefaultStatusCodeHandlerResult' to 'Nancy.Response''
 at CallSite.Target(Closure , CallSite , Object )

来源:Anonymously Hosted DynamicMethods Assembly

随后

Nancy.ViewEngines.ViewNotFoundException
     at Nancy.ViewEngines.DefaultViewFactory.GetRenderedView(String viewName, Object model, ViewLocationContext viewLocationContext)

没有任何关于异常的附加信息。

然后 REST 客户端显示错误 404

我定义错了什么?我遵循了以下示例:building-a-simple-http-server-with-nancy

如果您 运行 您的代码在调试器下 - 确保抛出的异常实际上未被处理。代码可能会抛出异常并且您的调试器(如果配置为这样做)可能会中断它们,即使这些异常已被处理(由某些 catch 块)。因为你毕竟收到了 404 回复而不是崩溃 - 我猜这些异常是 "normal" nancy 流程的一部分,因此被处理了。

至于 404 - 您的模块是内部模块,Nancy 不会发现它。改成 public:

public class MyWebModule : NancyModule
{
    public MyWebModule()
    {
        Get["/"] = _ => "Received GET request";
    }
}