A way to handle forms
The details
When developing an ASP.NET Core application, handling form submissions is a common task that you will encounter. In this blog post, we will discuss how to handle form submissions in an ASP.NET Core application using a middleware class.
The middleware class we will be using is called FormHandlerMiddleware. This middleware class checks the values of keys in the Request.Form collection to determine how to handle the form submission.
Here’s the FormHandlerMiddleware class:
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace MyNamespace
{
public class FormHandlerMiddleware
{
private readonly RequestDelegate _next;
public FormHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Method == "POST")
{
string addAnother = context.Request.Form["addAnother"];
string catRadio = context.Request.Form["catRadio"];
string anotherForm = context.Request.Form["anotherForm"];
if (addAnother == "yes")
{
context.Response.Redirect("/Home/CatsRadioPage");
}
else if (catRadio == "cat8")
{
context.Response.Redirect("/Category8/Interest");
}
else if (!string.IsNullOrEmpty(anotherForm))
{
// Do something for another form
}
else
{
// If form is not recognized, call the next middleware in the pipeline
await _next(context);
}
}
}
}
}
In this FormHandlerMiddleware class, we first check if the request method is “POST”. If it is, we retrieve the values of the “addAnother”, “catRadio”, and “anotherForm” keys in the Request.Form collection. If the value of “addAnother” is “yes”, we redirect to “/Home/CatsRadioPage”. If the value of “catRadio” is “cat8”, we redirect to “/Category8/Interest”. If the value of “anotherForm” is not empty, we perform some action for that form. If none of these conditions are met, we call the next middleware in the pipeline.
We can use the UseMiddleware extension method to add the FormHandlerMiddleware class to the application’s request pipeline. Here’s an example of how to use it in the Configure method of the Startup class:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseMiddleware<FormHandlerMiddleware>();
// ...
}
And that’s it! With this middleware class, we can handle form submissions in our ASP.NET Core application in a concise and easy-to-understand way.
I hope this blog post has been helpful in showing you how to handle form submissions in an ASP.NET Core application using a middleware class. If you have any questions or feedback, feel free to contact me via the ‘Get in touch’ link in the footer!