The Middleware_Sample application is a basic c# middleware implementation that checks the configuration file to determine if technical work is underway and prohibits API access is so. The application is developed on the .NET framework.
The project is implemented using the IOptions pattern to work with the configuration file. For more information about this pattern, see the Used links section.
If in appsettings.json configuration file IsTechnicalWorkInProgress is marked as true, this means that some technical work is being carried out on the service and access to the Web API is denied.
To run the AttributesSample application, follow these steps:
- Clone the repository:
git clone https://https://github.com/BorisMinin/Middleware_Sample.git
- Open the solution in Visual Studio.
- Build the solution.
- Run the program.
To use the Web API, you need to try out several scenarios:
- In the appsettings.json configuration file specify the true value for the IsTechnicalWorkInProgress key, which will signal the ongoing technical work on the service. In this case, when you start the project, you will receive an error message.
- In the appsettings.json configuration file specify the false value for the IsTechnicalWorkInProgress key, which will signal that no technical work is currently being carried out on the service. In this case, when you start the project, swagger will be launched and you will be able to use endpoints.
First scenario:
Second scenario:
appsettings.json configuration file:
"TechnicalWork": {
"IsTechnicalWorkInProgress": true
}
To create a custom middleware, click Add->Class->Middleware Class. The implementation of any technical requirements using middleware is performed in the Invoke method.
public async Task Invoke(HttpContext httpContext)
{
if (_technicalWorkConfiguration.IsTechnicalWorkInProgress)
{
httpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
await httpContext.Response.WriteAsync("Technical work in progress. Access is prohibited.");
return;
}
await _next(httpContext);
}
To learn more about creating custom middleware, see the Used links section.
Create custom middleware: https://www.tutorialsteacher.com/core/how-to-add-custom-middleware-aspnet-core
IOptions pattern https://andrewlock.net/how-to-use-the-ioptions-pattern-for-configuration-in-asp-net-core-rc2/