Create ASP.NET Web API Using Visual Studio 2022 (.NET 7)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video I will show you how to create an asp.net core web API using visual studio 2022 so I will show you how to create a new project using.net 7 and we will explore the structure of this project then we will see how to create an API controller and the actions that will handle the different HTTP requests and methods we will see how to return a specific type and also how to return different HTTP responses using iaction result then we will use a model class to transmit the data between the server and the client and finally I will show you how to make data validation and custom validation now let's create a new asp.net core web API so let's click on create a new project in this window we can select c-sharp then all platforms and here we can select web then we need to select this option it is asp.net core web API so if you cannot find this option then we need to scroll down then we have to click on install more tools and features then in this window we have to select this option it is asp.net and web development then we have to click on the install bot but in my case it is already installed so let's close this window and here we have to select asp.net core web API so let's select it then let's click on next then let's call this project web store API so it will be saved at this location of course it is possible to change it and now let's click on next in this window we have to select the version of.net so let's select.net 7 which is the latest version for the authentication type let's select none let's check this box to use https then we need to check this box to use controllers and finally let's check this box because we want to use Swagger to test our API now let's click on create now the project has been created so we can close this page and here we can see that in the controllers folder we have this controller it is called weather forecast controller let's open it so in this controller we can see that we have this attribute API controller this means that this controller is an API controller and does not respect the conventions of the MVC controller also we have this attribute route so here we can see that we have controller between brackets this means that this controller is accessible at the URL that contains the name of the controller without the controller word so this controller will be accessible at the URL that contains weather forecast now if we scroll down we can see that we have this method so this method is accessible using the HTTP get method and it will return a list of weather forecast objects so we can find whether forecast class in the solution just here so let's open this file and we can see that it is a model that contains these properties now let's test the application so we can click on this run button or also we can use this button to start the application without debugging so let's click on this button and because we are using a self-signed certificate to use the https we have this warning so let's click on advanced and let's click on this button accept the risk and continue in this page we can see that we are using swagger which is available on the local machine at this port number and also it is available at this URL slash Swagger index.html also we can see here that we have the name of our controller which is our endpoint so it is weather forecast without the controller word then we can use the HTTP get method to receive the data from the server so here let's click on this list so here we can see that we don't need to provide any parameters to send a request to the server also the response can be of type 200 which means a success response then the data that you can receive is a list of objects and the objects here are of type weather forecast which is the model that we are using inside the controller now to send a request to the server we can click on trade now then let's click on execute so here we can see that the request has been transmitted to this URL and we received this data so here we have a list of objects and we have five objects now let's update the controller to send 10 objects instead of 5. so here we have to update the get method and we have to change this parameter so let's write 10. now let's save the file and to restart the application we can either use this button or also we can use the hot reload feature so let's click on this button let's go back to the browser so let's click on this list then try it out then execute and this time we have 10 objects in the response so instead of clicking on the hot reload button each time we make a modification we can enable the automatic cut reload so let's go to visual studio and here let's click on this button then let's select hot reload on file save so now let's change this value and let's write 9 let's save the file and here we can see that the modifications have been applied so let's display five instead of nine let's save the file and the modifications have been applied again let's go to the browser let's click on this list then try it out then execute and this time we have five objects so here we can see that the server is running on this poor number and of course it is possible that we need to change it so later I will show you how to change this per number so this is the structure of our project and we can open this solution so let's make double click on it so in this file we can see that we are using version 7 of.net and here we have the list of packages which are already installed inside this project then we have the folder called properties let's expand it and it contains the launch settings file so let's open it so this file contains the configuration of the different profiles of this project so we can see that we have the HTTP profile and also we have the https profile then we have this profile IIs Express so these profiles are what we have when it when we click on this button so here we have HTTP https which is already selected and IIs Express so now I will show you how to update this profile so we have just to update this profile let's call it web API so this name should appear in this list when we save the file now let's update the port number of this application so for the moment it is using this per number and for example let's change it and let's write four thousand now let's save this file so let's click on this button and let's select this profile web API now let's run the application and now we can see that our web API is available on the port number 4000. the next file that we have here is this one it is upsettings.json so let's open it this file is useful to add some configuration parameters that allow us to configure our application so for example we can add the connection string that allows us to connect to the database also we can add some API keys that allows our web API to connect to other web apis and of course it is possible to add any type of parameters such as the application name the next file inside this project is this one which is program.cs this file is the principle file of this application it allows us to configure the application and is executed only one time when we start the application then we can add services to this application so a service is a class that can be used by the different classes of the application and we can add it inside the service container like this it will be available to the different classes of this application and then we can use the dependency injection to inject the service to the Constructor of the different classes of this application then here we can configure the pipeline of the application so the pipeline is a sequence of middlewares and filters which are executed sequentially before and after the execution of the controller so here we can see that when we receive a request it will enter to the pipeline which is a set of middlewares and the last middleware will execute several filters and then we'll execute the controller and then when we have a response the response will be also processed by the different middlewares and then will be transmitted to the client so here we can see that the middlewares are executed in a well-defined order and if we have any custom middleware it will be executed Just Between the authorization middleware and the endpoint middleware now let's delete this controller and let's create our own controller let's delete this model as well and now let's create a new API controller inside the controllers folder so let's make a right click then add then controller in this window let's select API then API controller empty then add then here let's select API controller empty and let's call it userscontroller.cs so this controller will be available at the URL API slash the name of the controller which is users of course we can change this URL also we have this attribute because this is an API controller now let's create the different methods that will process the different HTTP requests so first let's create a global variable of type list that will contain the list of users so just here we can create it it can be private or public so let's create it as a private variable and it should be static like this it will save the data over the different requests so it is static and it is a list of string values let's call it list users and let's initialize it so we can fill it with some data so the data is of type string so here let's add some string values then let's create the method that will return the list of users so this method will be accessible using the HTTP get method so here we have to add the HTTP get attribute then we have to define the method so it should be public it will return a list of string values and let's call it get users so we don't need to provide any parameter and we need just to return the list of users now let's create another method that will return only one user identified by its ID so we can copy the first method let's paste it here so let's call it get user and we need the ID of the user so here let's add a parameter called ID and to access to this method we have to add the ID of the user to the route so we can do it using this attribute so here between parentheses we have to add double quotes then between brackets we have to add the ID of the user so the name of this parameter should be the same as the name of this variable and then we have to return the user having this ID so the type of the return will be string and we will return the user having this ID so here we have to add between brackets the ID of the user but before returning this user we have to check that this ID is valid so just here let's add a condition so if the ID is valid then we will return the user having this ID otherwise we will return an empty string now let's create another method that allows us to add a user to this list so the new method should be available using the HTTP post method so just here we have to add the attribute HTTP post then let's create the method so it returns nothing so it returns void and let's call it add user so this method requires as the parameter the name of the user which is of type string let's call it username and then what we have to do is to add this user to this list now let's create another method that allows us to update a user so the new method should be available using the HTTP put method so just here we have to add HTTP put then let's create the new method so it is a public method that does not return anything and let's call it update user so here we need the ID of the user and also we need the username we can read the ID of the user from the route so just here we have to add parenthesis then double quotes and then between brackets we have to add the ID of the user so the ID that we will have inside the route will be the ID of the user that we want to update then we need to read the username from the body of the request so what we have to do here is to update the user having this ID so first let's check if the ID is valid or not so if the ID is valid then we will update the user having this ID finally let's create the method that will be executed when we receive an HTTP delete request so we have to add the attribute HTTP delete and then we have to add the ID of the user in the URL so between parenthesis we have to add double quotes then between brackets we have to add the ID of the user now let's create the method so it is a public method of type void and let's call it delete user so we need the ID of the user that we want to delete and we can find the ID and the route so here we have to check if the ID is valid or not so we can copy this code if the ID is valid then we can delete the user having this ID from this list let's save the file and let's run the application so here we can see that we have the name of the new controller without the controller word and also we have the list of HTTP methods that we can use so first let's see the list of users that we have so let's click on this list let's click on try it out then execute and here we can see that we have a list of four string values now let's create a new user so let's use the post method here let's click on trade out and then let's provide a name then execute so here we can see that the response is 200 which means a success response and the response is empty it has no data this is because the action that served the request returns void so it does not return any data now let's check that the new user has been added so let's click on the first list then here we can see that previously we have four users so let's click on execute and now we have this new user so this user is the last user of this list so it has the ID for now let's find this user by ID so we can use the get method that requires the ID of the user let's click on try it out then let's provide the ID for let's click on execute and we have this user now let's try to provide an ID which is not valid for example 40 then let's click on execute so here we can see that we still have the response to 100 which means success response but this time we have no data now let's try to update a user so let's click on this list let's click on try it out and let's update the last user with id4 so we have to provide the new username let's write Michael for example let's click on execute so here we have a success response with no data then let's use the first route which allows us to read all the users so initially the last user has this name Patrick and because we updated the name we should find Micro when we click on execute so let's click on execute and here we can see that the last user is now called Michael now let's delete a user so let's click on this list and let's delete the last user so here let's write four let's click on execute so here we have a successor response with no data and when we click on execute this last user should be deleted so here we can see that we have only four users now instead of returning a specific type we can return I action result this allows us to return different responses to the client so let's delete this type let's write I action result then let's check if this list contains data or not so if this list is not empty then we can return the data of this list so we have to write return okay of list users otherwise we can return no content then let's do the same thing with the get user so let's delete string let's write I action result and if the ID is valid then we will return this user so let's write okay then the user otherwise we will return not found let's do the same thing with this action so instead of void let's write I action result and after adding the new user to the list we can return ok now let's update this action so here let's delete void let's write I action result and after updating the user we can return ok so OK means that we will return the Response Code 200 which is a success response now for this method we have to do the same thing so let's delete void let's add I action a result and when we delete a user we can just return no content let's save the file and let's test the application let's read a user by its ID so let's click on this list let's click on trade out then let's provide a valid ID one for example let's click on execute so here we have a success response with the name of this user now let's try to provide the ID which is not valid for example let's provide 10 let's click on execute so here we have this response which means that the user is not found let's take a look on the action and we can see that the get user by ID will return not found if the ID is not valid now let's delete a user let's provide any ID one for example let's click on execute so here we have a success response with no date we can see that the delete user action returns no content now instead of using a simple data type which is string in our case we can use models so let's create a new folder inside this application let's call it models then we need to create a new model to store the data of the users this model will be used to store the data exchanged between the client and the server so it is called data transfer object model or dto module so here let's make a right click on models then add then class and let's call it user dto then let's create the different properties that will store the details of the user so they should be public so the first property is of type string and it is called first name let's initialize it with an empty value then let's create another property called last name and let's initialize it then let's create the email property then let's create phone and finally let's create the address property let's save the file then let's change the type of this list so instead of string let's write user dto so here we can see that we have this error this is because we need to add the namespace so let's select it and also let's write user dto just here let's delete these values and let's create a new user detail object then between these brackets we can Define the values of the different properties of this class so first we have the first name then let's provide a value for the last name then we have the email address then phone and finally we have the address then let's create a new user inside this list so we can copy this user let's add comma and let's paste this user so let's change the first name Also let's change the last name and let's change the email address let's update the phone number and we can keep the address as it is so here we don't need to update this method or this method and in the add user method we need to update this parameter so it will not be of type string so let's delete this type let's add user dto and let's call it user and let's add this user inside this list then let's update the update user method so here we can update this parameter it will be of type user DTU let's call it user so this method allows us to update a user and this is the new user so we have to replace this variable with user and here we can see that we don't need to update the delete user method now let's save the file and let's test the application now we can see that we have a new type and a schemas so this is the new model that we have created we can expand it and we can see that we have the first name the last name the email the phone number and the address so here we can see that every string in this model can be none now let's see the list of users let's click on execute so here we can see that we have a list of two users now let's create a new user so let's click on this list try it out and here we have to provide the first name the last name the email the phone and the address so let's delete this value and let's provide a valid value let's do the same thing with the other parameters then let's click on execute and here we have a response 200 which means a successful response let's take a look on the list of users execute and this time we have three users now let's update the last user so let's click on this list so the last user has the ID too and here let's provide the new values let's click on execute so here we have a successful response now let's take a look on the list of users execute and here we can see that the email address the phone number and the address have been updated now I will show you how to make data validation when we submit the data to the server so let's go to our model which is available in the models folder which is user DTU and here we need to add validation attributes so the first name is required so we have to decorate it using the required attribute so between brackets we have to add a required and here we can see that we have an error this is because we have to add the data annotations namespace also the last name is required so let's copy this attribute and let's add it above last name then we can customize the error message if we don't have the last name so here between parenthesis we can add error message and then we have to provide a string which is the error message so here we will use the default error message for the first name if the first name is missing but we will use this custom error message with the last name now let's decorate the email property so it is required and also it should have the email format so we can add another attribute it is called email address so we can add the two attributes on different lines or also we can add them on the same line separated with comma just like this then let's suppose that the phone number is optional so we will not decorate it using any attribute and finally the address is required so here let's add the required and also we can define a minimum length and a maximum length to the address so we can use additional validation attributes which are mean length and max length so the minimum length is 5 characters and if we did not respect this constraint then we can display the error message the address should be at least five characters and the maximum length is 1000 characters and if we did not respect this constraint then this is the error message so this is all what we have to do to implement the data validation because the controller will take care to verify the validation attributes when we submit a user to the server so let's save this file and let's test the application let's expand user dto and here we can see that we have some constraints so for example for the address it should have a minimum length equal to 5 and a maximum length equal to 1000. also the email property is of type email address now let's create a new user so let's click on the post list so let's provide an empty first name let's also clear the last name and let's provide an email address which is not valid and finally for the address we can keep it empty let's click on execute and here we have the validation errors for the different properties so the email address should be a valid email address the address is required and also it should be at least five characters then here we have for the last name please provide your last name which is our custom error message but for the first name the error message is the first name field is required which is the default error message now let's provide valid values let's click on execute so this time we have a success response with no data now let's update a user so the update action requires a user dto object that's why the validation will be also applied for the put method so let's click on this list let's provide the ID of the user that we want to update so let's update the last user with id2 and let's provide empty values let's provide an email address which is not valid and let's provide a short address let's click on execute so here we can see that we have an error message with the email with the address with the last name and also with the first name now let's provide valid values let's click on execute so this time we have a success response now I will show you how to add custom validation errors for example let's check that the email address is authorized so let's go to the add user method that allows us to create a new user and just at the beginning of this method let's check that the email address is authorized so for the moment let's add a comment so in our case we will check that the email address is not equal to user at example.com so if the email address of the user is equal to this value then we can display a custom error message to the user and we can return bed request so here we have to add model state DOT add the model error this is the name of the property that has an error and this is the custom error message and of course we will return bed request with the model state now let's do the same thing when we update a user so let's copy all of this let's go to the update user method and just at the beginning we can paste the code let's save the file and let's test the application let's create a new user so here let's keep this email address which is not authorized and let's click on execute and here we have our custom error message so it is an error message for the email address and this is the error message also we can see that the response is of type bed request
Info
Channel: BoostMyTool
Views: 5,553
Rating: undefined out of 5
Keywords:
Id: 5eS8Vy4Yxc8
Channel Id: undefined
Length: 39min 21sec (2361 seconds)
Published: Thu Mar 23 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.