简体   繁体   English

如何在 c# (wpf) 中启动 Nancy web 服务器

[英]How to start Nancy web server in c# (wpf)

I'm trying to start a simple Nancy web server (In a WPF project as I need to have some windows as well...) using this code:我正在尝试使用以下代码启动一个简单的 Nancy web 服务器(在 WPF 项目中,因为我还需要一些 windows ......)

public class ProfilePage : NancyModule
{
    public ProfilePage()
    {
        var host = new NancyHost(new Uri("http://localhost:8080"), new Bootstrapper());
        host.Start();

        Get("/", _ => { return $"Hello world"; });
    }

    public class SelfHostRootPathProvider : IRootPathProvider
    {

         public string GetRootPath()
         {
             return Environment.CurrentDirectory;
         }
    }
}

public class Bootstrapper : DefaultNancyBootstrapper
{
    protected override IRootPathProvider RootPathProvider
    {
        get { return new SelfHostRootPathProvider(); }
    }
}

When I run it, it just loads forever and eventually crashes with the following exception: System.StackOverflowException: 'Exception of type 'System.StackOverflowException' was thrown.'当我运行它时,它只会永远加载并最终崩溃并出现以下异常: System.StackOverflowException: 'Exception of type 'System.StackOverflowException' was throwed.'

Does someone know what have I done wrong?有人知道我做错了什么吗?

The NancyModule should only set up the routes and nothing else. NancyModule 应该只设置路由而不是其他任何东西。 There is also no need to reference the NancyModule in anyway, since it is picked up automatically by the bootstrapper.无论如何也不需要引用 NancyModule,因为它是由引导程序自动获取的。 Something like this should suffice:像这样的东西就足够了:

public class ProfilePage : NancyModule
{
    public ProfilePage()
    {
        Get("/", _ => { return $"Hello world"; });
    }
}

And then somewhere else, where you need to start your hosting:然后在其他地方,您需要开始托管:

using (var host = new NancyHost(new Uri("http://localhost:8080")))
{
   host.Start();
   Console.WriteLine("Running on http://localhost:1234");
   Console.ReadLine();
}

I think the problem you are seeing is that the host is starting, then trying to set up the routes, which starts by starting the host, which requires setting up the routes, which.... It's easy to see how it leads to StackOverflowException.我认为您看到的问题是主机正在启动,然后尝试设置路由,首先启动主机,这需要设置路由,这......很容易看出它是如何导致 StackOverflowException .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM