Search code examples
.netasp.net-coreasp.net-web-apimiddleware

.NET Custom Middleware to display a webpage/form


I am trying to figure out how I can create my own middleware, to provide a Form or Webpage.

It should be usable like HangFire or NSwager and it should work for .NET Core WebApp and WebApi projects:

app.UseHangfireDashboard();
app.UseSwaggerUi3();

So in my case i would like to use it like:

app.UseMyDashboard();

What it needs to do:

  1. Provide an endpoint (/myDashboard)
  2. This page contains a simple form
  3. Submit the form and execute some code

How do I do something like that ? Do I need to create a separate project for this? Because I want to reuse this in any other projects, meaning I want to pack this in a NuGet package and make it available for internal use.


Solution

  • I will provide you a brief answer to start with, you can go through the documentation https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1 for detais. To call app.UseMyDashboard(); from startup class you would need to create an extension method:

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    namespace YourNamespace
    {
        public static class MiddleWareExtension
        {
            public static void UseMyDashboard(this IApplicationBuilder app)
            {
                // 1. Provide an endpoint(/ myDashboard)
                app.Map("/myDashboard", app =>
                    app.Run(async (context) =>
                    {
                        //2. This page contains a simple form, Submit the form to redirect to another form
                        await context.Response.WriteAsync("<button onclick=\"window.location.href = '/path'; \">Click me</button>");
                    }));
                //3. Another Form
                app.Map("/path", app =>
                    app.Run(async (context) => await context.Response.WriteAsync("<b>New Form</b>")));
            }
        }
    }