I was working on one of the requirements, where I need to modify result data in middleware (not any MVC Filters due to some other services injected through middleware).
In middleware I was getting data in json format and then deserializing that data then updating that data and finally serializing to JSON and sending it back as a response.
I don’t want to serialize data in MVC pipeline so I tried to remove output formator but that didn’t work for me and throwing error.
services.AddControllers(options =>
{
options.OutputFormatters.Clear();
});
Is there any solution to get the .Net object in the pipeline and modify that object (as we do in MVC filter) and then serialize at last?
4
Answers
I am not sure whether it fits your requirements but you can use HttpContext to store some data in the scope of the request. There is a ‘Items’ key-value collection.
Beside the other suggestion to use
Items
of HttpContext, I want to note that you can inject services into Action Filters:Register to DI Builder:
Apply to action/controller:
Testing by accessing the URL:
Another alternative is to use DI service with
Scoped
lifetime.Service:
Register to DI:
Set data in Controller:
Your middleware that consumes it:
Test with the URL:
You can store data in HTTP context items.
In controller action:
In middleware: