-
Notifications
You must be signed in to change notification settings - Fork 1
Events
To make it easier to extend the middleware behavior, like aborting the request if not made from localhost or changing the response headers, there are two main events that should be considered.
Assuming the middleware will be executed, this event enables some custom logic to interact with the HttpContext instance before the middleware itself and if it aborts the request (using HttpContext.Abort) or anything is written to the response (setting HttpContext.Response.HasStarted to true, then the middleware code won't execute and a corresponding response will be returned to the client.
This event can used by setting the property SimpleSoftMiddlewareOptions.BeforeInvoke passed to the middleware. Here is an example were only authenticated requests will be accepted, otherwise an 401 Unauthorized will be returned:
new SimpleSoftMiddlewareOptions
{
BeforeInvoke = async ctx =>
{
if(ctx.User.Identity.IsAuthenticated)
return;
ctx.Response.StatusCode = 401;
await ctx.Response.WriteAsync("Unauthorized");
}
};To help implement some common cases you can use some methods from BeforeInvoke. As an example, if you wanted to only accept request from a local client, aborting the request otherwise:
new SimpleSoftMiddlewareOptions
{
BeforeInvoke = BeforeInvoke.LocalOnly
};Or if from a local client or administrator:
new SimpleSoftMiddlewareOptions
{
BeforeInvoke = BeforeInvoke.IsLocalOrHasAnyRole("admin")
};This event is triggered after the middleware executes (if allowed by the event BeforeInvoke) and can be used by setting the property SimpleSoftMiddlewareOptions.AfterInvoke.
Lets assume you wanted to add some extra logging when the middleware completed:
new SimpleSoftMiddlewareOptions
{
AfterInvoke = ctx =>
{
ctx.RequestServices.GetRequiredService<ILogger<SimpleSoftMiddleware>>()
.LogDebug("Response returned to the client");
return Task.CompletedTask;
}
};Remarks: Remember the response to the client was already started by the middleware, so what you can do here is very limited without causing an error and aborting anything being sent.