ASP.NET Core hosting

By Dawid on (tags: ASP.NET, core, hosting, categories: code)

Hosting is how you get you ASP.NET application up and running. And ASP.NET Core is just bunch of libraries host in you own process. It’s not provide a hosting – user have to take care of providing hosting process.

That gives us lot of possibilities and flexibility. Such application can be hosted in console application, windows service or everywhere you want – all you need to do is to build a host, get it started and start listening for requests. Bellow I will try to show you couple of examples of that.

Build the host

In few words all we need to do is to:

  • Setup host services – definition of the features which you server will provide
  • Configure a server – what server do we want to use
  • Identify startup logic – setup of all core hosting services (for example logger, hosting environment)
  • Build the app RequestDelagate – host will take the request pipeline logic defined in the startup logic and turn it into the Request Delegate. Request Delegate is the core abstraction of ASP.NET Core – it take the HTTP request and does something asynchronously with it.

Run the host

That is also quite simple, just:

  • Start the server from hosted app – simply start listening for requests
  • Handle requests using app RequestDelegate

Configuring hosting properties

There is couple of thing which have to be set up before we will be able to start our server:

  • Server – we have to decide if will use Kestrel, Web Listener or you will write your own server
  • Server URLs – address we want our server to listen on
  • Startup – here will be our startup logic
  • Content root – location where application stuff is (for example views, static files, javascript files). Those are typically handled by Static Files middleware
  • Web root – this is the place where we want static files middleware to look to expose static content
  • Environment – development, integration or production – that’s just a string
  • Application name – the name of the application

Code

How it looks like in code – for that you can create an empty ASP.NET Core project in Visual Studio and prepare something like that:

   1: public class Program
   2: {
   3:     public static void Main(string[] args)
   4:     {
   5:         var contentRoot = Directory.GetCurrentDirectory();
   6:  
   7:         var config = new ConfigurationBuilder()
   8:             .SetBasePath(contentRoot)
   9:             .AddJsonFile("hosting.json", optional: true)
  10:             .Build();
  11:  
  12:         //WebHostBuilder is required to build the server. We are configurion all of the properties on it
  13:         var hostBuilder = new WebHostBuilder()
  14:  
  15:             //Server
  16:             .UseKestrel()
  17:  
  18:             //URL's
  19:             .UseUrls("http://localhost:6000")
  20:  
  21:             //Content root - in this example it will be our current directory
  22:             .UseContentRoot(contentRoot)
  23:  
  24:             //Web root - by the default it's wwwroot but here is the place where you can change it
  25:             //.UseWebRoot("wwwroot")
  26:  
  27:             //Startup
  28:             .UseStartup<Startup>()
  29:  
  30:             //Environment
  31:             .UseEnvironment("Development")
  32:  
  33:             //Configuration - here we are reading host settings form configuration, we can put some of the server
  34:             //setting into hosting.json file and read them from there
  35:             .UseConfiguration(config);
  36:  
  37:         //Build the host
  38:         var host = hostBuilder.Build();
  39:  
  40:         //Let's start listening for requests
  41:         host.Run();
  42:     }
  43: }

All you need to do is just to start the application and start listening for requests!

Startup

What will be done with the HTTP requests depends on the Startup class. Bellow is the example of very simple Startup class which is writing “Hello world!” message into the output.

   1: public class Startup
   2: {
   3:     public void ConfigureServices(IServiceCollection services)
   4:     {
   5:         //here you can configure services which will be available for the application through Dependency Injection
   6:     }
   7:  
   8:     // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
   9:     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  10:     {
  11:         loggerFactory.AddConsole();
  12:         loggerFactory.AddDebug();
  13:  
  14:         if (env.IsDevelopment())
  15:         {
  16:             app.UseDeveloperExceptionPage();
  17:         }
  18:  
  19:         app.Run(async context =>
  20:         {
  21:             context.Response.ContentType = "text/plain";
  22:             await context.Response.WriteAsync("Hello world!");
  23:         });
  24:     }
  25: }