简体   繁体   中英

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:

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.'

Does someone know what have I done wrong?

The NancyModule should only set up the routes and nothing else. There is also no need to reference the NancyModule in anyway, since it is picked up automatically by the bootstrapper. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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