I implemented a middleware en .net core to read the request and verify if the attributeody of name is contained 2 times in the body of the request. I am getting grazy, I cannot figure out how is it possible the middleware is being called twice and the second time returns a 500 status error code. I only added the middleware once to the startup.cs, but anything I try is not working and the middleware is called twice, second one with an error. Please, help
public async Task InvokeAsync(HttpContext context)
{
var request = context.Request;
if (request.Method != HttpMethods.Post)
{
await _next(context);
return;
}
var requestBody = await ReadRequestBody(request);
if (Validation(requestBody))
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync("Duplicated fields");
return;
}
request.Body = new MemoryStream(Encoding.UTF8.GetBytes(requestBody));
await _next(context);
return;
}
STARTUP.CS
public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<SingleOccurrenceMiddleware>();
if (env.EnvironmentName != "Local")
app.UseHsts();
app.UseXRay("UKIAwardsCampaigns");
app.UseHttpsRedirection();
app.UseRouting();
#region NetCore 3.1 Middlewares migration
//Setup Cors from EnvironmentVar
app.UseCorsFromEnvironmentVar("ASPNETCORE_CORS_URLs");
app.UseAuthentication();
//Add a middleware to build a EnterpriseIdentity from a claims Identity
app.UseEnterpriseIdentity();
app.UseAuthorization();
#endregion
app.UseLocalization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
I implemented a middleware en .net core to read the request and verify if the attributeody of name is contained 2 times in the body of the request.
Actually, this is the expected behavior when executing a middleware twice because when an HTTP request executes usually two endpoints get hit. So the middleware executes twice.
If you debug your application, you would observe that first call would be executed for loading your application itself the base path should be your domain/local host or /
.
And for the second time, your application has its resouce file. For instance, css, js or any other internal file within your application root folder which need additional execution.
Please have a look at the following network trace log:
Therefore, you can check out your 500 error what causing this, but apart from 500 internal error, middleware execution twice is not a downsides.