ASP.NET Core modify/substitute request body

Take the request body, read its content, make whatever changes are necessary if at all, then create a new stream to pass down the pipeline. Once accessed, the request stream has to be replaced. public async Task Invoke(HttpContext context) { var request = context.Request; if (request.Path.Value.Contains(“DataSourceResult”)) { //get the request body and put it back … Read more

Modify middleware response

.NET Core 3+ solution with proper resource handling: Replace response stream by MemoryStream to prevent its sending. Return the original stream after the response is modified: public async Task Invoke(HttpContext context) { var response = context.Response; //uncomment this line to re-read context.Request.Body stream //context.Request.EnableBuffering(); var originBody = response.Body; using var newBody = new MemoryStream(); response.Body … Read more

How do I customize ASP.Net Core model binding errors?

It’s worth mentioning that ASP.NET Core 2.1 added the [ApiController] attribute, which among other things, automatically handles model validation errors by returning a BadRequestObjectResult with ModelState passed in. In other words, if you decorate your controllers with that attribute, you no longer need to do the if (!ModelState.IsValid) check. Additionally, the functionality is also extensible. … Read more