Carl Rippon

Building SPAs

Carl Rippon
BlogBooks / CoursesAbout
This site uses cookies. Click here to find out more

ASP.NET Core HttpHandlers? / HttpModules?

April 15, 2015
dotnet

In ASP.NET Core, both HttpHandlers and HttpModules are no longer needed because of the ability to now plugin to the request pipeline. This post details how to plugin into the ASP.NET Core request pipeline and handle requests for a given URL.

Pluging in to the pipeline

Startup.Configure() lets you plug middleware into the request pipeline using IApplicationBuilder.Use()

The parameter in IApplicationBuilder.Use() is a delegate that in tern has parameters giving the HttpContext and a delegate to the next piece of middleware.

The code below is an example of how to plug some code into the request pipeline. In this example, MyHttpHandler.ProcessRequest() is called during every request.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
    }

    public void Configure(IApplicationBuilder app)
    {
        // add our http handler to the request pipeline
        app.Use(async (ctx, next) =>
        {
            await Task.Run(() =>
            {
                MyHttpHandler MyHttpHandler = new MyHttpHandler();
                MyHttpHandler.ProcessRequest(ctx);
            });
            await next();
        });
    }
}

HttpContext is different

One thing to note is that the HttpContext class is a little different …

For example HttpContext.Request.Path is of type StringPath rather than String and HttpContext.Request.HttpMethod is now HttpContext.Request.Method.

Handling the request

The following code is the implementation of MyHttpHandler from the earlier example. It should output “This is my HttpHandler …” for the path /MyHttpHandler.

public class MyHttpHandler
{
    public void ProcessRequest(HttpContext HttpContext)
    {
        if (HttpContext.Request.Path.Value == "/MyHttpHandler")
        {
            HttpContext.Response.WriteAsync("This is my HttpHandler ...");
        }
    }
}

If we try this and browse to /MyHttpHandler you should get the following:

ASP.NET Core HttpHandler

If you to learn about using React with ASP.NET Core you might find my book useful:

ASP.NET Core 5 and React

ASP.NET Core 5 and React
Find out more

Want more content like this?

Subscribe to receive notifications on new blog posts and courses

Required
© Carl Rippon
Privacy Policy