Category Archives: Kestrel

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.