Let's perform the following steps:
- Create a new folder called Middleware within your project, and then add a new class called CommunicationMiddleware.cs, with the following code:
using Microsoft.AspNetCore.Http;
using TicTacToe.Services;
public class CommunicationMiddleware { private readonly RequestDelegate _next; private readonly IUserService _userService; public CommunicationMiddleware(RequestDelegate next,
IUserService userService) { _next = next; _userService = userService; } public async Task Invoke(HttpContext context) { await _next.Invoke(context); } }
- Create a new folder called Extensions within your project, and then add a new class called CommunicationMiddlewareExtension.cs, with the following code:
using Microsoft.AspNetCore.Builder;
using TicTacToe.Middleware;
public static class CommunicationMiddlewareExtension { public static IApplicationBuilder
UseCommunicationMiddleware(this IApplicationBuilder app) { return app.UseMiddleware<CommunicationMiddleware>(); } }
- Add a using directive for TicTacToe.Extensions in the Startup class, and then add the communication middleware to the Configure method:
using TicTacToe.Extensions; ... public void Configure(IApplicationBuilder app,
IHostingEnvironment env) { ... app.UseCommunicationMiddleware();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}
/{id?}");
endpoints.MapRazorPages();
}); }
- Set some breakpoints in the communication middleware implementation and start the application by pressing F5. You will see that the breakpoints will be hit if everything is working correctly:
This is just a basic example of how to create your own middleware; there are no functional changes visible between this section and the others. You are going to further implement the various functionalities for finalizing the Tic-Tac-Toe application in the next chapters, and the communication middleware seen in this chapter is going to do some real work shortly.