Category Archives: ASP.NET Core

More ASP.NET Core with C#

In the previous post I looked into the F# Giraffe library which makes writing all sorts of web request/response code pretty simple. This in turn is built on top of the existing functionality within ASP.NET Core.

Let’s again look at the bare bones code from running up Kestrel adding code to the pipeline

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

namespace KestrelTest
{
    public class Startup
    {
        public void Configure(
            IApplicationBuilder applicationBuilder,
            IHostingEnvironment hostingEnvironment)
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WebHost.CreateDefaultBuilder()
                .UseStartup<Startup>()
                .UseKestrel()
                .Build()
                .Run();
        }
    }
}

Within the Configure method we can start adding code to respond to different routes using the Map method, for example add the following to the Configure method

applicationBuilder.Map("/hello", app =>
{
   app.Run(async ctx =>
   {
      var request = 
         ctx.Request.Path.HasValue ? 
            ctx.Request.Path.Value.Substring(1) : 
            String.Empty;
       await ctx.Response.WriteAsync("Hello " + request);
   });
});
applicationBuilder.Map("/error", app =>
{
   app.Run(ctx => 
      Task.FromResult(
         ctx.Response.StatusCode = 404) 
   );
});

Note: The code is somewhat basic, obviously you would probably want to write some better code for extracting partial paths etc. from the routes/maps. However we’ll be covering a better alternative to this sort of code later in the post.

In the above we’ve created the equivalent of two “routes”. The first handles URL’s along the line of localhost:5000/hello/World where the return would become “Hello World”. The second route simply responds with a 404 for the URL localhost:5000/error.

We can also (as you’d expect) handle queries within our URL, so let’s say we expect this format URL, http://localhost:5000/hello?name=World, then we can amend our /hello code to the following

applicationBuilder.Map("/hello", app =>
{
   app.Run(async ctx =>
   {
      await ctx.Response.WriteAsync(
         "Hello " + ctx.Request.Query["name"]);
   });
});

These pieces of code write responses, but we can also insert code into the pipeline which doesn’t write to the response but instead might add debug/logging code. Other examples of usage might include (as per Writing Middleware) changes to the culture for the user response.

Here’s a simple example of such code, this is a little contrived as we’re going to (in essence) redirect calls to /hello path. Just place the following code before the applicationBuilder.Map method in the above

applicationBuilder.Use(async (ctx, next) =>
{
   if (ctx.Request.Path.Value == "/hello")
   {
      ctx.Request.Path = new PathString("/error");
   }
   await next.Invoke();
});

Note: there are redirect/URL rewriting capabilities already in ASP.NET Core, see URL Rewriting Middleware in ASP.NET Core.

Routing

In the previous example we demonstrated using the Map method to route our calls but ASP.NET Core libraries already supply a routing middleware which handles a lot of the standard routing type of functionality we’d expect. We can add the routing services by adding a method to the Startup class like this

public void ConfigureServices(
   IServiceCollection services)
{
   services.AddRouting();
}

Now the Configure method should look like this

public void Configure(
   IApplicationBuilder applicationBuilder,
   IHostingEnvironment hostingEnvironment)
{
   var routes = new RouteBuilder(applicationBuilder);
   routes.MapGet("hello/{name}", ctx =>
   {
      var name = ctx.GetRouteValue("name");
      return ctx.Response.WriteAsync($"Hello {name}");
   });

   applicationBuilder.UseRouter(routes.Build());
}

The RouteBuilder handles the routing in a more helpful/useful manner. Don’t forget to use the line applicationBuilder.UseRouter(routes.Build()); or you’ll find that the routes are not registered and hence your code will never get called.

References

ASP.NET Core MiddlewareRouting in ASP.NET Core

Using Giraffe as a service pipeline in Kestrel

In the previous post we looked at using Kestrel to run an ASP.NET Core application, now we’re going to use Giraffe to build some services.

Giraffe is an F# library to let get started by creating our application code.

  • Create Visual F# | .NET Core | Console App
  • My project is named GiraffeTest
  • Add via NuGet Giraffe and Microsoft.AspNetCore

Replace Program.fs code with the following

open Giraffe
open Microsoft.Extensions.DependencyInjection
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore

let webApp =
    choose [
        GET >=>
            choose [
                routeCif "/hello/%s" (fun name -> text (sprintf "Hello %s" name))
            ]
    ]

type Startup() =
    member this.ConfigureServices (services : IServiceCollection) =
        services.AddGiraffe() |> ignore

    member this.Configure (app : IApplicationBuilder) =
        app.UseGiraffe webApp

[<EntryPoint>]
let main _ =
    WebHost.CreateDefaultBuilder()
        .UseKestrel()
        .UseStartup<Startup>()
        .Build()
        .Run()
    0

In the previous post we saw how to create the Kestrel server, so the code in main is exactly the same (apart from obviously being F#) which creates the server and calls the Startup class to configure our middleware. In this case we add Giraffe to the services and runs the Giraffe webApp HTTP handler.

The webApp HTTP handler is basically our filter and routing function.

Run this code up and navigate to localhost:5000/hello/World and we should get Hello World displayed.

We didn’t actually need the GET handler as by default the GET will be used, but it’s shown here to be a little more explicit in what is being implemented. We can also support POST methods using the same syntax as our GET code.

Extending our routes

Giraffe allows us to declare multiple routes which can include static pages. Let’s start off my adding an index.html page to the “Content root path” as displayed when running the application, in my case this is the folder containing Program.fs. I’m using the following index.html

<html>
    <body>
        Hello World
    </body>
</html>

Now add a new route to the route section of the webApp. i.e.

choose [
    routeCif "/hello/%s" (fun name -> text (sprintf "Hello %s" name))
    route "/" >=> htmlFile "index.html"
]

This has now added a route for localhost:5000/ which returns the contents of the index.html file.

A list of different routes can be seen in the source for Routing.fs.

Below is an example of using some different routes

let helloName name = text (sprintf "Hello %s" name)

let webApp =
    choose [
        GET >=>
            choose [
                // case insensitive using anonymous function
                routeCif "/hello/%s" (fun name -> text (sprintf "Hello %s" name))
                route "/"       >=> htmlFile "index.html" 
                route "/error"  >=> setStatusCode 404
                route "/ping"   >=> text "pong"
                // case sensitive use function
                routef "/hello2/%s" helloName
            ]
    ]

Return from the fish (>=>) operator can be marked as different types of result types.
The functions text, htmlFile and other response writes available here ResponseWriters.fs. These include the usual suspects such as XML and JSON. Giraffe also supports Razor, see the NuGet package Giraffe.Razor.

References

Giraffe GitHub repos.

Kestrel – ASP.NET core web server

Kestrel is a .NET Core cross platform web server that can be used to host web sites, web/REST services etc.

Note: This code covers .NET core 2.0 and ASP.NET core 2.0.1

Take a look at Introduction to Kestrel web server implementation in ASP.NET Core for a great post about using Kestrel along with IIS, Nginx etc.

Getting Started

Let’s get started and build a very basic application running Kestrel.

  • Create a Visual C# | .NET Core | Console App (.NET Core) application
  • My project is named KestrelTest
  • Use NuGet to add the package Microsoft.AspNetCore

Now let’s create the most basic and most useless web server by writing the following code

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;

namespace KestrelTest
{
    public class Startup
    {
        public void Configure(IApplicationBuilder applicationBuilder,
            IHostingEnvironment hostingEnvironment)
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WebHost.CreateDefaultBuilder()
                .UseStartup<Startup>()
                .UseKestrel()
                .Build()
                .Run();
        }
    }
}

In Main we create the webserver and we supply the Startup application which we’d use to configure our services. Minimally we need the Configure method in the Startup object and notice we’re not adhering to any specific interface or type.

We could pass the args to the CreateDefaultBuilder if we want to start the application with certain arguments and/or use the UseKestrel override to create options for our server, but we’re aiming to just create the bare essentials of a Kestrel based web server in this post.

Now we can run this code and we’ll get, by default, a web server running and exposing port 5000 on localhost. However the server does nothing else, no static pages, nothing.

So let’s now add the NuGet package Microsoft.AspNetCore.StaticFiles and change our Configure method to look like this

public void Configure(
   IApplicationBuilder applicationBuilder,
   IHostingEnvironment hostingEnvironment)
{
   applicationBuilder.UseWelcomePage();
}

Now run the application and using your preferred web browser, navigate to localhost:5000 and you should see a ASP.NET Core Welcome Page.

Again this is of little use but does show that everything is working.

Serving up some static content

See Work with static files in ASP.NET Core for more in depth information.

Let’s now use Kestrel to serve up some static pages. Change the Configure method to look like this

public void Configure(
   IApplicationBuilder applicationBuilder,
   IHostingEnvironment hostingEnvironment)
{
   applicationBuilder.UseStaticFiles();
}

Now in your project folder (i.e. the folder with your Program.cs file) which should be the same as the Content root path shown when you run the application. Here you can add a wwwroot folder and place an HTML page in the folder, i.e. here’s a simply index.html file

<html>
    <body>
        Hello World
    </body>
</html>

Make sure you set the file to have the “Copy to Output Directory” option as “Copy if Newer” in the properties window in Visual Studio.

Run the application again and navigate to localhost:5000/index.html and you should see the text Hello World.

Middleware

As we’ve seen in this post, the design of Kestrel is to supply a default web server application which we can then add our middleware code to, turning the application into a static web server or adding ASP.NET MVC into the mix etc. We can implement our own middle ware (see ASP.NET Core Middleware) which can be used to handle requests via a middleware pipeline.

I’m not going to go into any real depth in terms of developing my own middleware as we can already use various libraries for this, but just to demonstrate how we can intercept a request, change the Configure method to look like this

public void Configure(
   IApplicationBuilder applicationBuilder,
   IHostingEnvironment hostingEnvironment)
{
   applicationBuilder.Run(async context =>
   {
      await context.Response.WriteAsync("***Hello World***");
   });
}

Now if we run up the application and navigate to localhost:5000 we should see ***Hello World*** returned.

References

Introduction to Kestrel web server implementation in ASP.NET Core
BenchmarksASP.NET Core Web Servers: Kestrel vs IIS Feature Comparison and Why You Need Both