Validating requests with FluentValidation | ASP.NET Core 5 REST API Tutorial 21

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
👍︎︎ 10 👤︎︎ u/celluj34 📅︎︎ Jul 29 2019 🗫︎ replies

I have been enjoying the series. I am a fan of fluent validation, but have one question why create a middleware for the validation when it is already built in and automatically uses the ProblemDetails document standard as the result?

👍︎︎ 2 👤︎︎ u/weisshole 📅︎︎ Jul 30 2019 🗫︎ replies

Amazing video series !

👍︎︎ 1 👤︎︎ u/m_umair_85 📅︎︎ Jul 29 2019 🗫︎ replies
Captions
hello everybody I'm Nick in this video I'm going to show you how we can start validating the incoming requests in our REST API in a speedloader core we're going to use a package called fluent validation for this purpose but I will also show you how we can do it without any other package and explain why fluent validation is a better approach at least in my opinion so let's go in our controller and we're gonna take a look at the tags controller and in here in the create endpoint we are creating a tag via a create tag requests so this is a request that the contract the API contract incoming it we're gonna validate and what I want to validate against is I want this tag name to not be empty and to not contain any special characters so only alpha numerics where we can do this by just code is just going here which is a great method and we can just say if request dot tag name for example the string dot is null or empty which means the tag name is an empty string then return that request and say something like error equals empty name however I'm gonna have to add such a string for every single one of these validations I want to do because I also want to do at my numerical checks and in the future I might also want to add other things here so obviously I cannot just have any statement for every single property of my contract so the other thing we can do is we can go here and don't let call support some attributes and those are able to can do validation so I could say I don't remember everything by heart but for example if I had a field called email or something and I wanted this to be an email address I would say email address and then if this value was false and I could say if model state is not valid so this automatically ties into the model state there returned and then I could translate the model state errors to API errors the reason why I don't like this approach either is because I'm gonna have to have this per the same code all over the place to check that the model state is not valid and then translate those errors to modern state errors or I also don't like this approach because we now have our validation logic or at least some of the validation logic on our contracts which it feels like it's breaking single responsibility principle I don't think that the model itself should know anything about how it needs to be validated so for that specific reason I don't want to have it here so how are we going to do this in a better way we'll here's where the project fluent validation is kicking in and I'm going to show you right now how we can make clean validation for our objects by the way I don't want you to confuse contract or request validation with business logic validation completely different things but we're going to see in the next video how they're gonna both return in the same way so I'm gonna introduce a new error model here which we're going to be returning and eventually everything should be using that very same contract and I will explain why so the first thing I want to do isn't going to go to nougat and I want to say fluent validation and I'm going to add the a spinet core package there reason why I'm going to add these packages because it comes with handy extensions that automatically register all our validators in our API let's see how we're gonna add this so I'm gonna go into my installers and this installer and this should be the add MVC line somewhere here oh here we go so let me just break it down a little bit so it's more readable and what I want to do is I'm gonna go here now say AB fluent validation so just that should be enough but we can also specify some configuration here and we're gonna say register automatically all the validators from an assembly and we're gonna say assembly containing our startup it's the same assembly scanning technique I showed you before and they should find everything that extends the abstract validator class so what is this abstract validator you might be asking so I create a new folder here and I'm gonna say validators so that's the name of folder and I'm going to create a new class and this class will be how was the contract named create tag request we're gonna copy that I'm gonna say create tag request validator and what this needs to do is it needs to extend the abstract validator and then we provide the name of the thing we want to validate so create tag request so absolute validator and the contract we're validating and then this class and the only thing we need to do is create a constructor and in this constructor we have this rule for method and what we wanna say is I want a rule for the tag name and what rule do we need what we need two rules first foremost this must not be empty so they're not empty rule and the other thing is it needs to match some regex and the regex is actually pretty straightforward in this scenario and doesn't matter if you're not familiar with regex it's I can get it's a very complicated thing this specific rule is very simple so I'm gonna just talk you through it so it says if they start with it contains a to z lower case or a to z upper case and then 0 to 9 numeric and then empty space husband occurs as we want and then ends here then this will validate alphanumeric characters and space it's not very complicated in this specific scenario but I know it can get very complicated in more complicated scenarios so here we have our two rules so this can file in two different ways the serval they don't know and because we have this MVC installer here it will automatically be registered in the I this means that now this validation will automatically be applied here and let me just show you that we're gonna say if model states is valid is false and I'm gonna stick a breakpoint here I don't gonna run the application so let's bring the UI here I'm already logged in so what I'm gonna do is I'm gonna say test create and I'm gonna put some special characters here so this should break into this breakpoint so this model state is no longer valid this is because this validator is now injected into our MVC framework and because we're validating against this contract the model step is invalid and at this point I could just look into the errors here and I could go to values or even keys and the keys will show me that the tag name property is bad it has a bad value and if I expand the errors I can say that the error name here is tag name is not in the correct format which is right because that's the default error code if something is not in the correct format the problem with this is that we're gonna have to do some translation here to some error model and then return that error model on every single control of one of the validation this is not a really elegant solution and we're gonna have to be repeating ourselves a lot before I show you how we can clean this up or when I go in the contract and I want to create some contracts here we come to contracts the first one is the error response and this will be the response from now on that we're going to turn on every single thing that returns something so an error and what we need is a list of error what the error model could be or code do not add this UI once we're gonna create our own type of this and you can say errors here and I'm gonna say that initialize it with a new list of our model I'm gonna copy that I'm gonna create a new error model here and we need two things one is the field name and this will be a string and what this field name is for is just to let the consumer know that this specific field is the one with the error and then we also need a friendly message to display so the same message imagine if this is an application like a mobile app it will automatically get this field name and then say okay I'm going to have to show this message under the specific field name for validation purposes so if I go back we should be resolved now yep it's all fine and now we have our response we are going ahead and we're going to create a feature I haven't talked about many where and lot in this series yet and that's because we didn't need them until now but in this video I'm gonna do this file - thing with a mid we're essentially a filter is a typed Whitworth so I'm gonna create a directory I'm gonna say filters and we are going to make a new class named validation filter and this filter will be implementing the eye a sync action filter interface and let me just implement this method now what is a mini well very briefly a middleware is just a single step in our application pipeline so the MVC pipeline goes like something hits my API I'm doing this then this thing is calling the next step in the pipeline and this thing is doing this so imagine like request comes in I'm validating that the user is authorized this is one where I'm checking that the model set is correct and this is another mid where I'm doing something in the controller and then I'm returning and there might be other Midwest well in the very beginning of the pipeline you might actually have a log middleware that just checks how long the request took and then log some data about it but very briefly just imagine like a step and this validation is what will happen before we get into the controller in fact this awaits the next thing this delegate call here if I change to nicing this is actually what we call the controller to go ahead and do some stuff what we're going to do is so imagine this like before controller after controller and what we're going to do is before the controller is being hit we want to validate the Moodle state and how are we going to do that well at this point the Moodle site is actually set because the validator has already done the validation what we want to do here is just get two invalid state and return this state to the user how we're going to do that we're gonna say if context dot model state dot is valuing as if it's not valid then we're gonna do some stuff first we want to get all the errors in the modern state so errors in model state equals context dot model state dot we're and we're gonna say where X dot values value sorry dot errors is more than 0 to make sure that we have some where's there sorry errors dot count is more than 0 of course and then we're gonna say I'm going to return it as a dictionary so to dictionary and then key value pair key key value pair yeah and I'm gonna return the key value pair key and then keep value where you want per dot value dot arrows dot select and we're gonna be selecting the error message field and we're gonna say to array and now we have a dictionary with the error field and the error name while the description and what an additional like error response equals new error response and then I'm going to have a nested for each loop the first one is there is no state so goes here and then these errors can have some errors so each field can actually have multiple reasons to be to be giving an error back so for that reason I say for its sub error in those errors create a new error model so our model equals new error model and then if you say Phillip I'm sorry sweet name equals to error dot T the key should be the name and then sub error dot and the summer is actually just a message so I don't need to do anything and the last thing I need to do is I must say our response dot errors dot add and I'm going to add the error model and this we populate this error response and I do not return it now so how would you do this I'll say context dot result and I'm going to say new bad request object result and we're going to return TR response and I also need to return because if I don't then this will call the next video where I'm going to get an exception because I already set the result here so this is all we need to translate this if I go back they should all be enough for me to actually test this out if I remove this code before we test this there's a single thing we need to do and this is to register the filter in the MVC pipeline so what I'm going to do here let's say we go in this add MVC method in our installer or startup and we save options dog filters don't add we are saying a valid dae-jung I had typed properly a validation filter and this is enough so I'm gonna run this obligation now and tested some application is running so if I try to create a new tag just execute this tag is created so if I list them the tags here but let's try to put some special characters here like these symbols and we gonna say execute and now we get an error contract back saying errors freak name tag and what's wrong with it well tag name is not in the correct format of course if I also change this to empty and I execute then it says tag name must not be empty so we're getting an appropriate description based on the validator we set now you can always customize that if you want to with that with error code extension of course this means that we need to validate or try to think we want to validate so in our post controller if I go here and I go to the create post request I also might want to have validation in the name of the post all the tags or whatever and ideally you would want same validation here because we are creating tags at this point but you should be following the same pattern so we just go here rule for what we want to validate against and then we say what we want you can also have custom validation here if I just do rule for the tag name again I could say must and the Mast method accepts a predicate so I could do all the custom logic in the world I would say contains special text and this will also validate against that but this is for more advanced scenarios this is all I wanted to show you in this video live like if you like this video subscribe more content like this and we'll see you the next video keep coding you
Info
Channel: Nick Chapsas
Views: 34,564
Rating: 4.9514823 out of 5
Keywords: Elfocrash, elfo, coding, asp.net, .netcore, dot net, core, C#, how to code, tutorial, asp.net core, javascript, js, 2.2, csharp, rest, rest api, development, lesson, software engineering, dev, microsoft, microsoft mvp, .net core, nick chapsas, chapsas, fluentvalidation .net core, fluentvalidation, rest api tutorial, .net 5, dotnet 5, dotnet, .net
Id: Ut6mRRFT2vM
Channel Id: undefined
Length: 17min 2sec (1022 seconds)
Published: Mon Jul 29 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.