Self-hosting a C# Nancy Server on Linux

Sinatra is a popular and wonderful web application framework that has spawned a number of copycat frameworks. You can write large websites or REST servers with it. While it is a framework only for Ruby, there are alternatives for other languages, Spark Java for Java, Lavarel for PHP, etc. For C#, Nancy is the choice, and you can avoid using ASP.NET if you’d like. This post shows how to set up a “Hello world!” Nancy project that will build and run on Ubuntu and Windows.

Prerequisites:

Method:

  1. In your Windows host machine, start Visual Studio.
  2. In Visual Studio:
    1. Create a new C# console application “hn” within the mapped directory for the virtual machine.
    2. Replace the contents of Program.cs with the following code:
      using System;
      using System.Collections.Generic;
      using Nancy;
      using Nancy.Hosting.Self;
      
      namespace hn
      {
          public class SampleModule : Nancy.NancyModule
          {
              public SampleModule()
              {
                  Get["/"] = _ => "Hello World!";
              }
          }
      
          class Program
          {
              static void Main(string[] args)
              {
                  var uri = new Uri("http://localhost:80");
                  List list_uri = new List();
                  list_uri.Add(uri);
      
                  HostConfiguration hostConfigs = new HostConfiguration()
                  {
                      UrlReservations = new UrlReservations() { CreateAutomatically = true }
                  };
      
                  using (NancyHost host = new NancyHost(new DefaultNancyBootstrapper(), hostConfigs, list_uri.ToArray()))
                  {
                      host.Start();
                      foreach (Uri u in list_uri)
                          Console.WriteLine(u);
                      Console.WriteLine("Press any [Enter] to close the host.");
                      Console.ReadLine();
                  }
              }
          }
      }
      
      
    3. In order for this to compile, you will need to add two packages using the Package Manager.
      1. Start the Package Manager in Visual Studio.
      2. At the prompt, type Install-Package Nancy and Install-Package Nancy.Hosting.Self.
    4. Compile and run.
    5. In a browser, type in “http://localhost/”.
      1. Verify that your browser displays “Hello world!”.
  3. In the virtual machine guest:
    1. Open a Terminal.
    2. cd <mapped-directory>/<project-directory>
      1. Make sure the directory is mapped and you see the new project.
    3. xbuild
    4. mono bin/Debug/<project-executable>
    5. In a browser, type in “http://localhost/”.
      1. Verify that your browser displays “Hello world!”.

 

dokku@kukku:/vagrant/hn$ ls
App.config  bin  hn.csproj  hn.sln  obj  packages  packages.config  Program.cs  Properties
dokku@kukku:/vagrant/hn$ xbuild /target:Clean
XBuild Engine Version 12.0
Mono, Version 4.2.2.0
Copyright (C) 2005-2013 Various Mono authors

Build started 2/24/2016 10:20:58 AM.
__________________________________________________
Project "/vagrant/hn/hn.sln" (Clean target(s)):
	Target ValidateSolutionConfiguration:
		Building solution configuration "Debug|Any CPU".
	Target Clean:
		Project "/vagrant/hn/hn.csproj" (Clean target(s)):
/vagrant/hn/hn.csproj:  warning : Project has unknown ToolsVersion '14.0'. Using the default tools version '4.0' instead.
			Target CoreClean:
				Deleting file '/vagrant/hn/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs'
				Deleting file '/vagrant/hn/obj/Debug/hn.exe'
				Deleting file '/vagrant/hn/obj/Debug/hn.exe.mdb'
				Deleting file '/vagrant/hn/obj/Debug/hn.csproj.FilesWrittenAbsolute.txt'
		Done building project "/vagrant/hn/hn.csproj".
Done building project "/vagrant/hn/hn.sln".

Build succeeded.

Warnings:

/vagrant/hn/hn.sln (Clean) ->
(Clean target) ->
/vagrant/hn/hn.csproj (Clean) ->

	/vagrant/hn/hn.csproj:  warning : Project has unknown ToolsVersion '14.0'. Using the default tools version '4.0' instead.

	 1 Warning(s)
	 0 Error(s)

Time Elapsed 00:00:00.5218600
dokku@kukku:/vagrant/hn$ xbuild
XBuild Engine Version 12.0
Mono, Version 4.2.2.0
Copyright (C) 2005-2013 Various Mono authors

Build started 2/24/2016 10:21:05 AM.
__________________________________________________
Project "/vagrant/hn/hn.sln" (default target(s)):
	Target ValidateSolutionConfiguration:
		Building solution configuration "Debug|Any CPU".
	Target Build:
		Project "/vagrant/hn/hn.csproj" (default target(s)):
/vagrant/hn/hn.csproj:  warning : Project has unknown ToolsVersion '14.0'. Using the default tools version '4.0' instead.
			Target PrepareForBuild:
				Configuration: Debug Platform: AnyCPU
			Target GenerateSatelliteAssemblies:
			No input files were specified for target GenerateSatelliteAssemblies, skipping.
			Target CoreCompile:
				Tool /usr/lib/mono/4.5/mcs.exe execution started with arguments: /noconfig /debug:full /debug+ /optimize- /out:obj/Debug/hn.exe Program.cs Properties/AssemblyInfo.cs obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs /target:exe /define:"DEBUG;TRACE" /nostdlib /platform:AnyCPU /reference:packages/Nancy.1.4.3/lib/net40/Nancy.dll /reference:packages/Nancy.Hosting.Self.1.4.1/lib/net40/Nancy.Hosting.Self.dll /reference:/usr/lib/mono/4.5/System.dll /reference:/usr/lib/mono/4.5/System.Xml.Linq.dll /reference:/usr/lib/mono/4.5/System.Data.DataSetExtensions.dll /reference:/usr/lib/mono/4.5/Microsoft.CSharp.dll /reference:/usr/lib/mono/4.5/System.Data.dll /reference:/usr/lib/mono/4.5/System.Net.Http.dll /reference:/usr/lib/mono/4.5/System.Xml.dll /reference:/usr/lib/mono/4.5/System.Core.dll /reference:/usr/lib/mono/4.5/mscorlib.dll /warn:4
			Target _CopyAppConfigFile:
			Skipping target "_CopyAppConfigFile" because its outputs are up-to-date.
			Target DeployOutputFiles:
				Copying file from '/vagrant/hn/obj/Debug/hn.exe.mdb' to '/vagrant/hn/bin/Debug/hn.exe.mdb'
				Copying file from '/vagrant/hn/obj/Debug/hn.exe' to '/vagrant/hn/bin/Debug/hn.exe'
		Done building project "/vagrant/hn/hn.csproj".
Done building project "/vagrant/hn/hn.sln".

Build succeeded.

Warnings:

/vagrant/hn/hn.sln (default targets) ->
(Build target) ->
/vagrant/hn/hn.csproj (default targets) ->

	/vagrant/hn/hn.csproj:  warning : Project has unknown ToolsVersion '14.0'. Using the default tools version '4.0' instead.

	 1 Warning(s)
	 0 Error(s)

Time Elapsed 00:00:01.0865300
dokku@kukku:/vagrant/hn$ mono bin/Debug/hn.exe

Unhandled Exception:
System.Net.Sockets.SocketException: Access denied
  at System.Net.Sockets.Socket.Bind (System.Net.EndPoint local_end)  in :0 
  at System.Net.EndPointListener..ctor (System.Net.IPAddress addr, Int32 port, Boolean secure)  in :0 
  at System.Net.EndPointManager.GetEPListener (System.String host, Int32 port, System.Net.HttpListener listener, Boolean secure)  in :0 
  at System.Net.EndPointManager.AddPrefixInternal (System.String p, System.Net.HttpListener listener)  in :0 
  at System.Net.EndPointManager.AddListener (System.Net.HttpListener listener)  in :0 
[ERROR] FATAL UNHANDLED EXCEPTION: System.Net.Sockets.SocketException: Access denied
  at System.Net.Sockets.Socket.Bind (System.Net.EndPoint local_end)  in :0 
  at System.Net.EndPointListener..ctor (System.Net.IPAddress addr, Int32 port, Boolean secure)  in :0 
  at System.Net.EndPointManager.GetEPListener (System.String host, Int32 port, System.Net.HttpListener listener, Boolean secure)  in :0 
  at System.Net.EndPointManager.AddPrefixInternal (System.String p, System.Net.HttpListener listener)  in :0 
  at System.Net.EndPointManager.AddListener (System.Net.HttpListener listener)  in :0 
dokku@kukku:/vagrant/hn$ sudo mono bin/Debug/hn.exe
http://localhost/
Press any [Enter] to close the host.

2016-02-24 (1)

 

Code for this example:

For more information:

 

Leave a comment

Your email address will not be published.