Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Recommended way to read the Request.Body in an ActionFilter #5260
changed the title from
Reccommended why to read Request.Body in an ActionFilter
Recommended why to read Request.Body in an ActionFilter
Sep 9, 2016
Are you trying to prevent developers from implementing validation logic in Filters? After reading the docs, this is not one of the use cases for ActionFilters.
If you must do this inside an action filter then you'll need to buffer the body (new up a memory stream and copy to it, replace the body). ModelBinding runs before action filters so if you have form data or a
If you can tell us more about what you need to accomplish we can suggest alternatives
Hi @rynowak thanks for your answer. I don't have to validate in the ActionFilter, I just though this would be a good place to put the validation logic before I call the controller method. I use the FromBody in the Controller class to get the data. Can I access this in an ActionFilter?
If not I can always do the validation from the controller class inside the method.
Yes, if you're inside an action filter then
Created a blog about this. thanks
Interestingly, if you try to update the model (as I am doing with inbound open id connect claims), the validation has already occurred. You have to force it to validate again.
I tried using a resource filter so I could catch it first, but I couldn't figure out how to determine the object type (which would tell me I needed to insert the data into the model). I can't always assume there is just one model coming in, right? One of the incoming models might not have the properties I need to update.
So I loop through, find the models that need updating, make the updates and then force validation again.
Doesn't sound very efficient, but I can't figure another way to do it. Any suggestions/pointers would be great.
Thanks for the articles and the answers here. Huge help.