We're All Doing Model Validation Wrong In Asp.Net Core!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
model validation in asp.net core is easy isn't it well yes but we'll still do it wrong if we place modeled radiation in the controller that's obviously not clean and it's obviously wrong should we place model validation in an action filter that's much cleaner but we can clearly do better so what's that stay tuned and we'll find out thank you hey there and welcome to the code wrinkles Channel model validation in asp.net core is something that we do almost day in and day out and there are several approaches to it but mainly all approaches they rely on the model state so the question is where should we exactly perform the model validation our first instinct would be to do it in the controller because it is straightforward and even have the model stayed just there however this is not clean and from my point of view that's the reason why this is quite wrong because it just cluttered the controller with some concerns that shouldn't be there at all the next approach which is also my favorite is to perform the validation in an action filter and that keeps the code quite clean the only thing is that we will need to decorate our actions that we want to run model validation on tweet our model validation filter and there's also another part to it because this can become a little bit tricky in some cases what we have here is a very basic setup first of all we have our API contracts you have the error response which is the primary reason why we want to have model validation in our asp.net core because in case of model validation failures we want to return our custom error contract and we have this post create which is our contract for incoming requests when we want to create a new post and we also have this validation filter which is an action filter we inherit this action filter attribute and we override this on action executing method and the only things that we do here is obviously if the model state is not valid we construct our own instance of error response and we set this as a result of bad request object result with our own error object now the problem is that if we run the application now it will be a little bit tricky and the model validation will actually fail or it will not return the result that we would expect let me run this application and here we have our Swagger documentation and let's just try it out now I will place here a string that's only three characters long and then we will execute the request and look at the result and the result is already here however if we look at the result object we notice that this is the default validation result that comes from asp.net core it is not our custom error contract and that's why validation or model validation in action filters is a little bit tricky so let me close this down and also stop the application the problem here is that asp.net core has a filter for invalid models and that filter is actually or has a higher percentage than than our filter here and this means that if we have model failures that filter kicks in and returns a response before we even get into our own filter now obviously the way to resolve or there are different approaches to to resolve this most of them are wrong but the most common approach that I have seen is to Simply remove this API controller attribute from the controller but this is really not recommended because if you do this you remove a lot of other features that you might still want from an asp.net core API like contract negotiation and things similar to that so that's something that we wouldn't do another approach would be to tweak with this validation filter and instead of overwriting this on action executing we'll have the override to own result executing in this case we need to also change this to result executing context and everything will still work and actually in this case as we or as our filter is or our method here is operating on the result executing and missed it by the time that the filter the asp.n core filter will try to set a response we are notified and we run our custom logic so then in that case this response will be generated and we would have or we would end up having with having our Custom Contract here however this is a little bit hacky and it's certainly something that we wouldn't like to do so this is obviously not a best practice and I wouldn't recommend that and let's do it the right way to do it the right way we need to come here to this program.cs file and here what we need to do is we need to configure a behavior in our API that will suppress that default filter that asp.net core uses if the model validation fails so we could do something like this Builder Services configure API Behavior options so this is the options pattern that we use here and we get these API opens and we get to configure them and all these options on API Behavior options we have this property suppressed model State invalid filter is set to true and if we run the application now we'll see that we get our custom response back so now everything is working fine so now that we understood the caveats about model validation in action filters then the question what's wrong with that and the answer to this is that well obviously we have moved some code into our action filter class and that's quite okay but if we take a look at our controller action we still have kind of like to use that attribute we need to write a line of code that shouldn't actually be there from my point of view so on my standards this is not 100 clean and I am a big fan of this Paradigm of aspect oriented programming so the question is what if we can just wire something up and we don't have to clutter every controller action that we want to run radiation only the filter so those were my thoughts when I entered the Twitter discussion with a user called Armin and he suggested some weird things for me at that point that we should use some kind of factories to perform model validation and at the first glance it seemed to be a little bit counter-intuitive for me at least it would make the code from my point of view at that specific moment harder to understand and harder to read the discussion went then on and as a certain point I had some something like a Eureka moment everything made sense again and there is really a way to perform more validation in a way that we don't touch the controller at all and it's actually also very easy to implement and straightforward to understand so let me show you the response on how we can do this right is still in this API Behavior options because if we take a look here into these options and then we place these two PC that we have different members here and one of the members is these invalid model State response Factory and we see that this is actually a funk that takes in an action context and that should return an iaction result so it means that theoretically if we can create a method that returns an eye action result and that takes in an action executing context then we can provide that specific method here to this funk and it will then work out of the box it means that what it will happen is that asp.net core at that point will use our own method to create that custom error response and not the default model State invalid filter we can even move this from here totally now let's go here to the error response because what I'll do here in this case I will add just a new method that would be a static method here for public static I actually thought remember the funk returns an action result and takes in an action context that's exactly what we do here now we only need the logic that we need to place here in order to create our custom model or custom error response but this is something that we already have here in this validation filter now the thing is that in this validation filter we don't know exactly if the model state is valid or not but in that factory if that is used and it is created we know that the model is not valid so in this case we can just even not take into consideration this entire if statement and just copy everything that we have in this if statement and just move it here in this aesthetic method now the only thing that we need to do here is not to set the context but we want to return because as we know this phone should return this I action result and now we should be good to go now let's take this generic model and let's go back to our program.cs and let's just provide here so it would be then error response and then we'll have this generate error response the only thing that we still need to do is come back to our controller and just remove and I will comment out for now this validate model now we can run the application and let's test it out let's provide a string that is just the characters long and let's click execute and if we take a look at our response model we see that it is indeed our error contract and it is not the default contract that asp.net core has this approach should work on virtually all asp.net core versions now in dot Net 7 we have even some more fancy stuff that we could deploy to perform model validation but as most production code bases out there probably don't run on.net 7 I will stick in this video to this approach this comment that is common for all asp.net core versions so as a conclusion we can observe that moving the model validation in API Behavior options allows us to declutter completely our controllers from any trace of model validation so we don't even need a model gradation attribute anymore if you enjoyed this video please hit the thumbs up button and like it so it you will make it easier to discover for others and if you are for the first time on this channel please hit the Subscribe button and the notification Bell so that you are always notified when there is anything new on this channel and if you have any question or just want to get in touch with me feel free to head over to the comment section and leave your question there or your comment and I would be more than happy to get in touch with you this being said thank you very much for watching and until the next time I wish you the very best
Info
Channel: Codewrinkles
Views: 9,867
Rating: undefined out of 5
Keywords: model validation, model validation asp.net core, asp.net core model validation, asp.net core rest api, asp.net core course, asp.net core tutorial
Id: JrGCPUkEgSU
Channel Id: undefined
Length: 10min 3sec (603 seconds)
Published: Thu Apr 06 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.