ASP.NET Web API Model Validation (Implemented in .NET 6 and C# 10)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to dotnet course central in today's video i am going to talk about model validation so in most cases when we deal with a web application or web api web application essentially calling web api behind the scene it will call the endpoints necessary for accessing data now those data can be coming as a post or get and in both cases it is important that we do some sort of validation and those validation can be done a number of ways but one of the way and the easiest way to do is through attributes provided out of box by the framework and then using a model state which is also available part of every controller so to demonstrate that what i have is i have a user controller which has a get and a post method the get method is a simple method which takes a name and our goal will be to validate this name parameter similarly post method takes an user object and our objective will be validate the user object to validate the user object what we are going to do is we are going to use attributes which are part of system dot component model dot data annotations and that is what we are going to use to validate so here what we can do is we can start with the name and say name is a required attribute so we will provide required as an attribute and i will add the name space here system dot component model dot data annotation similarly for age for example we want the age to be between 0 and 99 so we can add a range attribute here and we can say minimum value is 0 and maximum value is 99 similarly for date we can have an attribute and i'll come to that later and for email what we can do is we can have for email we can say a email is an email address so we can use the email address attribute for that similarly for phone we can have an attribute called phone which will ensure that it is a phone number or a number as such and for address let's say we want to use the address should be required but it can be an empty string also so for that what we can do is we can use allow empty string is equal to true so in that case you have to pass an address but you can pass it as an empty string you cannot omit the object from the json so here is you can see in this example itself we see the option of a required which means it has to be always passed range where we can validate a range for an integer or double value then we have an email address which we can validate through email address we have a phone phone number which we can validate through phone number attribute and then we have an address which is also required but we are going to allow an empty string for this and membership and date something which i'm going to come back and show two different ways of two other different ways of validation when we come to that i am going to take these two into account so now let's run this application and if we run this application we are going to use multiple option in the post because if you remember the post takes the user object so during post we can have multiple ways validate the whole process so the ui is up and now we can click on the post and here if you want to try out see how everything is already coming in the format because we defined those attributes now if we run this phone phone number is a string it is not in a number format so if i execute this we're going to add get there that phone number field is invalid so here if i provide any number it is going to work fine and if i execute now we get 200 back now let's change this to one zero one now we're going to get an error for the age and you can see the field age should be between 0 and 99 let's put it back to 99 and if we change the email here just get rid of this and execute the email is going to throw an error so as you can see there are multiple ways we can validate an object just using attributes which we have defined and that is about it it's just the attribute defined in the model allows us to validate all the things in the model now the other thing we can do is if we go back to these for a string parameter for example this name we can also have something called string length where we where we can define what should be the maximum length so for name let's say we want the maximum length to be 10 and then we can also provide things like specific error message here so i can give error message and i can say name is to big so now let's run this application again and this time for the name property if we pass more than 10 characters we are going to get an error and the error message is going to say the name is too big so now after swagger shows up i'm going to try to post this i'm going to try it out let me change the phone number to some integer value some number value basically and here for the name i can give one two three four five six seven eight nine ten eleven twelve and if i execute this this time see it is saying that name is too big and this is the message which is thrown by the model itself so this is extremely simple implementation if you look into the api itself i'm not doing any validation as such given that i defined the model with all the validation attribute it is automatically done by the framework and only if the model is valid it is going to go and execute rest of the code so this is pretty cool feature which comes with the api and model validation so now the next thing i wanted to cover is let's say for this date what we want to do is we want to have a way to validate the date in such a way that the date is has to be greater than or equal to 2022 so for that what we can do is we can say this particular user object derives from i validatable objects so we are going to implement this interface and this interface comes with a single method called validate it has a validation context here so what we can do is here all we have to do is what is our goal our goal is if the date is less than 2022 we want to throw an error essentially so we can say if date that's our property dot year is less than 20 22 then yield return we are doing an ill return because it has to return a validation result inemorable hence we are doing an yield so ill return new validation result and here we can give our error message which is date is incorrect let's say that's our message and now if we run the application again this time what i'm going to do is i'm going to change the date property and i'm going to change it to 2021 and execute and this time it should throw the error for invalid date so here i'm going to go into post i'm going to try it out first let me give some number to the phone number and for the date here i'm going to change it to 2021 execute and in the response we can see we got a 400 response date is incorrect as expected so this is another way to create validation on model it's just to implement a interface eye validatable object interface and then insert the validate method you can write anything you want for validation and this gives you a very easy way to isolate the implementation of validation now if you want to go one step ahead and i personally don't like this code in the model itself because it looks a little bit ugly in my opinion so i would personally prefer to create an attribute which is going to help us do that so we can do that and let's say we want to implement some logic for the membership and let's say for the membership we want to but before we go to membership one thing i did not show is the address address is required but it will allow empty string so let's show that also because i don't think i covered that before so let me run the application now okay so now i'm going to go back here try it out let's give some number and here for address if we put empty string run we still get 200 no problem but if i'm going to get rid of this node all together and try to execute now i am going to get an error that address field is required so as you can see we can make it required but empty okay now back to the membership scenario so let's say we have membership for the user and we want to have a specific logic for the membership property itself and in case of certain membership we want to allow this particular api this particular api this action on user post we want to allow only for some membership and not for some so to do that what we can do is we can create another attribute and i can name it as membership validation attribute and the membership validation attributes class let me first fix the namespace here the membership validation attribute class is going to derive from validation attribute base class which is also part of system dot component model dot data annotations and this class so for this class what we have to do is we can override the method is valid and we'll take the one which is the validation context and then what we can do is we can say var user is equal to validation context dot object dot object instance as user the validation context the object instance of the validation context should be containing the model that we are trying to validate or the model on which we are going to use this attribute and then here we can say if user dot membership dot tooler is equal to trial so we are if the membership of the user is trial we don't want to allow this particular feature so we are going to say then not allowed and otherwise we are going to return validationresult.success if it's not a trial user then just allow only for trial user block this particular feature and then we'll go here and here we are going to add attribute so it's a membership validation so now i'm going to run this and this time we are going to change the membership value to trial and then we'll see that the validation is going to fail and it is going to throw an error and this is how we can use a custom attribute to validate certain properties and the other advantage of using custom retribute is that you can use you can create a custom attribute for validation and it can used across multiple objects if you want to so first let me change the phone number to some number and here let's give it as trial and execute and here you can see we got a 400 not allowed so as you can see it is extremely powerful and simple to use the validation framework of dot net six this is here i'm using dot net six and c sharp ten and it is super simple just to define all your validation in the object itself through attribute in worst case you can use an i validatable object interface you can implement that and provide an implementation for the validate method and the other way if we don't want to do it is creating custom validation and i personally prefer creating custom validation attribute and finally let's say what we want to do is we want to validate something like this a string what we can do is we can use the validation attribute here as well now here let's say we want to validate the name and we want to make sure it is only a to z the name is between a to z so we can use regular expression validation so you can use regular expression i have to add again the system dot component model.data annotation namespace and here for the for the expression i'm going to provide a regular expression which will ensure that this is just a string between a to z so for that what i'm going to do is i'm going to write this expression a to z capital a 2 capital z and plus dot should be it so now if i run this and this time we are going to test the get we have not tested the get yet we were testing the pose because that was expecting the user object as a parameter so now after the swagger loads up we can go and test the get user and here if we provide test one two three and try to execute it is failing now it is not intuitive from here because when we're not seeing the error so i'll show you how we can see that so first let's prove that it is working as expected now i can copy this endpoint open up a new tab and paste it here and here i can give user one two three if i give that user one two three you can see we're getting 400 error and it says the field name must be regular expression this now we can change this error message also but for the time being this is this is how we can write regular expression validation on a string parameter into a get method so and here if we want to change the error message we can always keep the error message is equal to and we can say name is incorrect let's say that's our message and we can try it out and now instead of showing the regular expression in the error message it is going to show the error message that we have provided in the attribute so that way we can control the messaging as well so once it loads up i can go back and i can try it out and i can say test here and then let me copy this again and i can try it out here and i can say test one two three and you can see here this time the error message is as we expected name is incorrect this is a very simple way of implementing model validation and input validation as part of web api which is available with the dotnet framework itself it is also this same model validation is also available for lower version of the framework even in dotnet framework four point star but when web api with dot net 6 one advantage i see is that we don't have to write any expression here to validate it is kind of already taken care of otherwise you will have to use model state dot is valid property to find out if the mod model is valid or not and throw an exception now in this case you don't have to do it's automatically taken care of so that's all i wanted to cover for today's video if you like this video please give me a thumbs up if you are new to my channel and if you think you are getting value out of my channel please subscribe to my channel and thanks so much for watching this video
Info
Channel: DotNet Core Central
Views: 12,234
Rating: undefined out of 5
Keywords: web api model validation, asp.net 6 web api model validation, .net 6 api model validation, asp.net web api model validation, asp.net web api model state validation, asp.net 6 web api model state validation
Id: sVZLhHEkGWk
Channel Id: undefined
Length: 21min 28sec (1288 seconds)
Published: Mon Mar 07 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.