In this post, I’m going to modify the request body by adding an additional field to the request body using middleware.
The middleware will try to read the current request body, add the additional field and then replace body with the new content.
public class CustomiseRequestBodyMiddleware
{
private readonly RequestDelegate _next;
public CustomiseRequestBodyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Method == HttpMethods.Get ||
context.Request.Method == HttpMethods.Delete)
{
await _next(context);
return;
}
context.Request.EnableBuffering();
var bodyAsText = await new StreamReader(context.Request.Body).ReadToEndAsync();
if (string.IsNullOrWhiteSpace(bodyAsText))
{
bodyAsText = "{}";
}
var jsonPayload = JObject.Parse(bodyAsText);
jsonPayload.Remove("AdditionalField");
jsonPayload.Remove("additionalField");
jsonPayload.AddFirst(new JProperty(
"AdditionalField",
JObject.FromObject(new { NewField = "I'm a new field" })));
context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(jsonPayload)));
context.Request.ContentLength = context.Request.Body.Length;
await _next(context);
}
}
Then we need to register this middleware in the startup class.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseMiddleware<CustomiseRequestBodyMiddleware>();
That’s it. Every request to your API will now have an additional field
AdditionalField = { NewField = "I'm a new field" }