ViewModels in ASP.NET Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to Create ViewModels in ASP.NET Core. It's our 9th tutorial in ASP.Net Core series. We have already covered Controllers, Models & Views in our previous lectures and now it's time to understand this fourth pillar of MVC architecture. ViewModel is not an integral part of MVC architecture and can be ignored in simple projects but in complex applications, we have to use ViewModel as it adds flexibility in the project. So, let's have a look at ViewModels in ASP.NET Core:

ViewModels in ASP.NET Core

  • ViewModels in ASP.NET Core ( also called Data Transfer Objects [DTO] ) are used to send Models data from Controller to View.
  • Normally in complex cloud based applications, data from multiple Model classes needs to be displayed in a single View file, in such cases it's wise to first combine all the incoming data in a single ViewModel file and then attach this ViewModel class with respective View.
  • We can place ViewModels anywhere in our project but to keep the project files organized, it's better to place all ViewModel files in a folder named ViewModels, as shown in the figure on right side.
  • Inside this ViewModel folder, I have added a new C# file and named it HomeInfoViewModel.cs as this ViewModel is for Info action method of Home Controller, its a convention to place ViewModel at the end of the filename.
  • Inside this ViewModel class, I have just added two properties, ViewModel code is shown in the figure on right side.
  • You can see in the code that first property is of type Engineers, which is from our Model Class Engineers.
  • While the second property is just a string for Page Title, if you remember in the last lecture, we have hard coded the Page Title in our View file.
Edit Home Controller File
  • Now open your HomeController.cs file and in the Info action method, add this code shown in figure on right side.
  • In Info action method, I have created a new instance of this ViewModel and have provided values for its properties i.e. first Engineer data & Page Title.
  • Finally I have passed this ViewModel object to respective View.
  • You must be wondering why we need to create this new file and have added extra code, it seems lengthy with single Model data but when you are working with 10 or 20 Models and you have to display their data in single View file, then ViewModels prove really helpful.
Update Info View File
  • Finally, we need to update our Info.cshtml View file according to this new ViewModel.
  • Code is shown in the figure and you can see that now I am using @model directive for ViewModel class now.
  • Moreover, I am now using properties of that ViewModel using @Model and now we just have the HTML code and rest is coming from C#, thus making it more flexible.
  • Now if you run your project, you will get the same results as in our previous lecture, but now the project is more organized and easily readable, here's the output:
So, that was all about ViewModels in ASP.NET Core. I hope you have enjoyed today's tutorial and if you have any questions, please ask in comments. Have fun !!!

Views in ASP.NET Core MVC

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to Create Views in ASP.NET Core MVC. It's our 8th tutorial in ASP.NET Core series. In our 6th lecture, where we have set up MVC architecture, we have also created Controller & Model, but we haven't yet created any View to display this data properly. We have also seen Dependency Injection and have successfully injected Model Interface in our Home Controller.  So, now it's time to add a View in our project and communicate it with Controller & Model. So, let's get started with Views in ASP.NET Core MVC:

Views in ASP.NET Core MVC

  • View in ASP.NET Core ( File Extension: .cshtml ) is a simple HTTP template, which displays the Model data, provided by the respective Controller.
  • By Convention, when View is called by the Controller, then MVC architecture first opens the "Views" folder, after that it makes a search for the Controller's Name folder i.e. "Home" folder and then finds for the file named after Action Method, from which it's called.
  • Let's understand this naming convention with an example:
  • Suppose I want to create a new page on my application, where I want to show engineer's info, so it's link will be:
  • In the above figure, home is our controller's name and this info has to be the name of the Controller's action method.
  • So, open your HomeController.cs file and add a new action method named info, as shown in below code:
  • You can see in above code that I have added a new action method in my HomeController class named Info and this method will be called when a user enters this address: domain.com/home/info/
  • The return type of this action method is ViewResult and that's because I am returning View in this method.First I have created an object having the information of first engineer and then I passed this object to my View and returned it to user.
  • So, you can clearly see that Controller is getting data from Models and then passing this data to View and then returning this View to the end user, who has actually entered the link and called this action method.
  • One more thing, you should notice in above code is that I am now inheriting my HomeController class from base Controller class and that's why I am able to use this View helper method in it.
We have created the action method which is calling our View but we haven't yet added the View in our project, so let's do that:

Creating View file in ASP.NET Core

  • First of all, create a folder named Views in the root directory using Solution Explorer.
  • Inside this Views folder, I have created another folder named Home, because our Controller's name is Home. So, all it's Views will be placed inside this Home folder.
  • Inside this Home sub folder, I have added a new Razor View file named Info.cshtml, as its the name of our action method in Controller class, shown in the figure on right side.
  • We will discuss Razor Views in detail later but for now they are smart HTML files where we can also add C# code.
  • We use C# code to display data coming from the Models via Controllers.
  • In order to add C# code, we need to use '@' sign and for lengthy code, we use curly brackets { }.
  • So, here's the code, which I have added in this new Razor View file named Info.cshtml:
  • You can see that above code is a simple HTML code with few C# code lines in it, so let's understand them.
  • In the first line of above code, I have added a @model directive to specify the model namespace, whose data is going to represented by this View.
  • In our case, its Engineers Model which has all our data properties, so now our compiler will know that Info View is dealing with Engineers Model.
  • Now, in order to print data from this attached model, we need to use @Model and then the data property.
  • @model directive starts with small 'm' while @Model property starts with capital 'M'.
  • So, now let's run our application, and open the link /home/info/ and if everything goes fine then you will get similar results:
  • You can see in above figure that we have data of our first engineer on our newly created Razor View.
So, that was all about Views in ASP.NET Core MVC and I hope you have completely understood the working of MVC architecture by now. If you have any problems in MVC then ask in comments and I will sort them out. In the next lecture, we will have a look at ViewModel in ASP.NET Core. Till then take care & have fun !!!

How to setup MVC in ASP.NET Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to setup MVC in ASP.NET Core. It's our 6th tutorial in ASP.NET Core series. So far, we have covered all the basic concepts in ASP.NET Core and are now ready to get our hands on MVC. If you remember, when we were creating this project in Introduction to ASP.NET Core, we have selected Empty Template as we want to build our application from scratch. But if you want, you can also select MVC template and all these files, which we are going to create, will automatically be created in it. So, let's see How to setup MVC in ASP.NET Core:

How to setup MVC in ASP.NET Core ???

  • MVC in ASP.NET Core is an architectural design pattern, implemented by Microsoft.AspNet.Mvc package and composed of three components, which are:
    • Model
    • View
    • Controller
  • When a user makes an HTTP request in the browser, this request is received by the Controller, which in turn targets the respective Model.
  • After being called by the controller, the model interacts with the database and also implements different operations on the data or request.
  • Controllers, not only select the respective Models, but also select the respective Views and pass on the data from Models to Views.
  • Here's a graphical representation of How MVC architecture works:
  • Now let's setup MVC in ASP.NET Core, so open up your Startup.cs file and in the ConfigureServices Method, we need to add required MVC Services.
  • This ConfigureServices Method is a Dependency Injection Container, so if we need to register any dependency in our application, we do it here.
  • As you can see in the figure on right side that we have added services.AddMvc() in our Dependency Injection Container.
  • Next, we need to add MVC Middleware in our Configure Method, so let's do it
  • As you can see in above code that I have added "MVC with Default Route" Middleware in my request processing pipeline.
  • When we add this MVC Middleware in our pipeline, by default it makes a search for Home Controller & then finds index Method in it.
So, now we have successfully setup our MVC Middleware and now it's time to understand its components one by one. So, first let's have a look at Controller.

Controllers in MVC

  • Controllers in MVC architecture are simple C# Classes, inherited from builtin Microsoft.AspNetCore.Mvc.Controller class and are used to handle incoming HTTP requests.
  • All public methods / functions in Controllers are normally referred as action methods i.e. we can invoke these methods using a specific URL and can perform required action / task.
  • Name of each Controller class is followed bu the word "Controller" i.e. if I want to create a Controller class named Home then it's file name will be HomeController.cs.
  • Now let's create a new folder titled Controllers in our Solution Explorer and add a new Class File in it named as HomeControllers.cs, as shown in figure on right side.
  • I have used MVC with default route Middleware, which has a default route for homepage and if you check its definition, then you will see that the default Controller is Home and the default action method is index.
  • So, now open this HomeController.cs class and add a new index Method in it, as shown in below figure:
  • As you can see in above code that I have added a new index Method in HomeController and that's the default home path for MVC Middleware.
  • So, now let's run our project and have a look at the browser and if everything goes fine then you will get this line printed on your homepage, instead of index.html file.
I hope you have understood the basics of Controllers, now let's have a look at Models in MVC architecture:

Models in MVC

  • Models in MVC architecture consists of different classes & interfaces which are requested by the Controllers and then perform different operations on the data objects.
  • Models are normally used to interact with the data sources i.e. getting or saving data & then this data is displayed on respective MVC View.
  • So,let's create a new folder named Models in our Solution Explorer and also add a new Class file in it named Engineers.cs, as shown in figure on right side.
  • As our site is related to Engineering, so I am going to create a new sign up form for engineers, so I have added below code in my Engineers.cs file:
  • So, we have created these properties in our Engineers Class and as you can see this Model class contains only our data.
  • We haven't added any Method to play with this data, so it's a data class.
  • Now we are going to create another class which will have all the Methods i.e. saving this data in database table or search for any data etc.
  • But before creating this class, let's first create its Interface in Models folder named IEngineersRepository.
  • In this interface, I have declared only one Method rite now but we will add a lot more in coming lectures, so here's it's code:
  • As you can see in above figure that have declared a method named GetEngineers(), which will get the Engineers data from database using its Id.
  • Now, let's create this second class, which will be implementing this Interface IEngineersRepository.
  • So, create a new class in Models folder and give it a name EngineersRepository, code is shown in below figure:
  • As you can see in above code that I have inherited this class from Interface IEngineersRepository, that's why it has the implementation of GetEngineers() function.
  • Before that Method Implementation, I have just added some hard coded data in the constructor of this class.
  • So, every time this class is instantiate, our data will be created, we will replace this data with SQL Database later but for now let's understand the MVC concept.
  • So, now we have two classes & one interface in Models folder.
In today's tutorial, we have a detailed overview of MVC architecture in ASP.NET Core. This tutorial isn't complete yet as we haven't yet discussed Views in MVC, but before discussing Views, we have to first understand Dependency Injection in ASP.NET Core, which is our next tutorial. After that, we will add Views in our project. Till then take care & have fun !!!

Dependency Injection in ASP.NET Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at Dependency Injection in ASP.NET Core. It's our 7th tutorial in ASP.NET Core series. In previous versions of ASP.NET, dependency injection was not its core element, although we could have achieved it using third party packages i.e. Ninject, StructureMap etc. As ASP.NET Core is built from scratch so it was made sure that Dependency Injection should become its essential part. In our previous lecture, we have created Controller & Model for our core project. Now there's a need to connect them together and that will be done by Dependency Injection. So, let's get started with Dependency Injection in ASP.NET Core:

Dependency Injection in ASP.NET Core

  • Dependency Injection in ASP.NET Core is used to inject dependencies in Web Application and these dependencies are mentioned in IoC Container, implemented by IServiceProvider.
  • In Startup.cs file, the ConfigureServices Method is dependency injection container and if you check it's parameters, then you will find IServiceProvider in it.
  • There are different types of Dependency Injections available and the most commonly used one is Constructor Injection.
  • In our Startup.cs file, we have seen two Methods: ConfigureServices and Configure.
  • So far, we have only discussed Configure Method, which is used to set up Request Processing Pipeline and we add our Middlewares in it.
  • But we haven't yet discussed the ConfigureServices Method, which is an IoC Container and is used for service configuration required by our application.
  • We can configure both builtin and custom services in this ConfigureServices Method.
  • In our previous lecture, we have added an MVC Service (builtin) in this IoC container, as shown in below figure:
  • Similarly, we can also create custom dependencies in ASP.NET Core and these custom dependencies will also be registered in this ConfigureServices Method.
  • In our previous lecture on MVC architecture, we have created an Interface named IEngineersRepository and a class implementing this interface named EngineersRepository.
  • In our future coding, we will never invoke this class, as its an implementation and we don't want to directly call this class as it will make our code rigid. Instead, I will always call this Interface as it's just a definition. ( If you are not getting this point yet, don't worry we will cover it in detail later)
  • So, now we have to insert this dependency so that if someone wants to use any method from Interface IEngineersRepository, compiler should know that it has to invoke the method from class EngineersRepository, without actually calling the class.
  • So, let's add this dependency using AddSingleton Method, as shown in below figure:
  • You can see in above code that in a single line, we have declared our dependency i.e. our interface IEngineersRepository is dependent on class EngineersRepository.
  • Now in our project, whenever we invoke this interface IEngineersRepository, compiler will know that I have to look in EngineersRepository class.
We have added the dependency condition in our Dependency Injection Container. But remember one thing that we haven't yet connected Model and Controller. We have just connected a Model Class with a Model Interface. So, now let's have a look at Constructor Injection in ASP.NET Core:

Constructor Injection in ASP.NET Core

  • When we want to inject one service into another then we use Constructor Injection in ASP.NET Core.
  • The service, we want to inject, is provided as a parameter to the Constructor of the service, in which it is being injected.
  • In our example, we want to inject our Interface IEngineersRepository in our Home Controller so that we could use its methods, as shown in below figure:
  • I have encircled the constructor injection code with red line, and you can see that I have created the Constructor of Home Controller and then passed interface as a parameter.
  • Finally, simply saved the value in private variable _engineersRepository.
  • In the action method index(), I have used this variable and then called the method GetEngineers, which is implemented in my class and will provide me the data based on Id, which I have provided 1. ( Rite now value is hard coded, we will automate it soon )
  • So, I am getting the university name of engineer with Id = 1, and if you remember we have hard coded the data and the university of first student was MIT.
  • So, now let's run this project and if everything goes fine then you will get similar results:
  • So, let's summarize our lecture, we have used dependency injection and then called Model function from home controller.

Why we need Dependency Injection ???

  • When you are working on some complex application, then we want it to be as flexible as we can and here dependency injection comes quite handy.
  • With Dependency Injection, we can bound different parts of our application together.
  • Let's say you have created some Interface named "IEngineersData" and then a class implementing it named "EngineersProfile".
  • Now in order to implement Constructor Injection, you first have to configure it in the ConfigureServices Method so that compiler could know that this class is implementing that interface.
  • In future, if you want to change the implementation of your Interface, you just need to change the name in this IoC Container.
I know it's not making much sense rite now and is a bit difficult to understand, but no need to worry as in our upcoming lecture, we will have a look at practical implementation of these concepts. So, that's all for today, in our next lecture, we will have a look at Views in ASP.NET Core. Till then take care & have fun !!!

Environment Variables in ASP.NET Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to use Environment Variables in ASP.NET Core. It's our 5th tutorial in ASP.NET Core series. In our Startup.cs file, you must have seen that we have an IF Condition at the start and this IF Condition has IsDevelopment in it. This condition is actually checking the environment of our web application. So, here we will first discuss them and then will see why we need them. So, let's get started:

Environment Variables in ASP.NET Core

  • ASP.NET Core has 3 builtin Environments, which decides the Run-time operating environment of the web application, which are:
    • Development.
    • Staging.
    • Production.
  • In order to set this Environment Variable, we need to open the launchSettings.json file, in the Properties section of Solution Explorer.
  • This launchSettings.json file has two profiles in it and both of these profiles have a variable ASPNETCORE_ENVIRONMENT, this variable is used to set the Environment value.
  • In the above code, you can see that we have set the value of ASPNETCORE_ENVIRONMENT to be Development, that's why we are in Development mode.
  • Let's discuss these 3 environment variables one by one:
Development Environment
  • As the name implies, when we are developing the application then we are in Development Environment, so the value of this variable should be Development.
  • In Development mode, we can show many details for understanding which we can't directly show to our end user.
  • At the start of this Configure Method, you must have seen IsDevelopment, its a builtin ASP.NET Core Boolean function, which is checking the Environment.
  • If the Environment is Development then show the Developers Exception Page and as this page has a lot of useful information, we can't show this information to our user, it will be dangerous.
  • That's why, we have placed this check that if we are in the Development Environment, only then show this Exception Page. ( We will discuss Exception Page later in detail )
Staging Environment
  • When you are developing complex cloud platform web application, then before transferring it to Production Environment, you first have to test it out in Staging Environment.
  • Staging Environment is quite equivalent to Production Environment and is normally for QA purposes to have a final look before publishing.
  • You can also use IsStaging function just like IsDevelopment in ASP.NET Core.
Production Environment
  • When you are fully confident that your application is complete and follows all security protocols etc. then you can set the Environment to Production.
  • If you remove this ASPNETCORE_ENVIRONMENT code line from the lauchSettings.json file, then by default, the runtime Environment is Production.
  • We also have IsProduction function to use in ASP.NET Core.
Custom Environment
  • We can also create a new custom environment in ASP.NET Core, we just need to specify this new name i.e. TEP in the launchSettings.json file.
  • Now, in order to check the custom environment, we need to use IsEnvironment("TEP") function, as shown in the code on right side.
  • We can use any name for this custom environment, we need to use custom environments in such application where we need to use separate profiles i.e. teacher, student, parents etc.

Developer Exception Page Middleware

  • As we have discussed the Environments, so now let's have a look at this Middleware Developer Exception Page.
  • It's another builtin ASP.NET Core Middleware, which shows an Exception Page to the Developer, if there's any exception occurs in your application.
  • This exception page is very helpful, as it gives detailed information about the exception or the issue occurred in the application.
  • We don't want to show this Exception Page to our end user as it reveals a lot of information related to our app, which could be helpful in hacking stuff.
  • So, that's why we have placed it inside IsDevelopment condition.
So, that was all about Environment Variables in ASP.NET Core. In the next tutorial, we will have a look at MVC architecture in ASP.NET Core. Till then take care & have fun !!! :)

How to handle Static Files in ASP.NET Core

Hello friends, I hope you all are having fun. In today's tutorial, we are going to have a look at How to handle Static Files in ASP.NET Core. It's our 4th tutorial in ASP.NET Core series. If you inspect your localhost page displaying Hello World, then you will see that there isn't any HTML code in it. Instead, it's just displaying Hello World in text format. In today's tutorial, we will have a look at How to add HTML, JavaScript, CSS or any other static file in ASP.NET Core. In our previous tutorial, we have discussed Middleware in ASP.NET Core, so if you haven't studied that then have a look at it first, as we are gonna use some new middleware components today. So, let's get started:

How to handle Static Files in ASP.NET Core

  • By default, ASP.NET Core doesn't allow us to handle / serve static pages and we can add this functionality using Static File Middleware.
  • In the Solution Explorer, right click on your Project's Name and then click on Add > New Folder and rename it to wwwroot, as shown in below figure:
  • All the static files ( JavaScript, CSS, HTML, Images etc. ) in ASP.NET Core has to be placed inside this wwwroot folder, which is called Content Root Folder, and this folder has to be directly inside the project's root folder i.e. Project's Name.
  • Now let's create three folders inside this wwwroot folder for CSS, JavaScript & Images, as shown in below figure:
  • In the above figure, you can see that I have created three folders and have also added an image in the images folder.
  • You could change these folders' names but its a convention to use these names, it helps in keeping things organized.
  • So, now let's access this image in the browser i.e. open this link http://localhost:51640/images/image1.jpg but still you won't get the image, instead it will still display Hello World.
  • In order to access this static file i.e. image1.jpg, we have to add a new middleware in the request processing pipeline.
  • So, open your Startup.cs file and in the Configure Method, add Static Files Middleware, as shown in below figure:
  • You can see in above figure that I have added app.UseStaticFiles() middleware, it's a builtin middleware of ASP.NET Core, which enables the web App to use static files in wwwroot folder.
  • After adding this Middleware, now when you open your image link then you will get your image in the browser, as shown in below figure:

Default Home Page in ASP.NET Core

  • We can also create a default HTML Home Page in ASP.NET Core using a builtin middleware Default Page.
  • This Default Page middleware search for one of the following files in wwwroot folder:
    • index.htm
    • index.html
    • default.htm
    • default.html
  • If the middleware finds any of the above titled files in wwwroot folder, it will make that file default page or homepage.
  • So, let's first create an index.html file in the wwwroot folder, as shown in the image on right side.
  • In order to add this index.html file, right click on wwwroot folder and then Add > New Item.
  • In the next window, make a search for html page and rename it to index.html.
  • Here's the code for that HTML file, I have just added the required HTML along with an H1 tag.
  • Now let's add the Default Page Middleware in our Configure Method in Startup.cs file.
  • The Configure Method is shown in figure on right side & you can see that I have removed the End Points Middleware.
  • Moreover, I have added a new Default File Middleware before Static File Middleware.
  • This Default File Middleware doesn't serve the default file itself, instead it just change the request path towards default file, this file is then served by Static Files Middleware, next in the pipeline.
  • So, if you place this Default Files after Static Files, then it won't work because files are served first and then default path is set. So, again emphasizing on this point: Position of Middleware matters a lot.
  • So, now if you run your web Application, then you will get this index.html file as home page, shown in below figure:
  • Now let's have a look at another ASP.NET Core builtin middleware named File Server Middleware.
File Server Middleware
  • File Server Middleware combines the functionality of three middlewares in ASP.NET Core, which are:
    • Default Files Middleware.
    • Static Files Middleware.
    • Directory Browser Middleware. ( it gives us information about directories i.e. file no. etc. )
  • You can see in the code that I have removed Default Files & Static Files Middlewares & replaced them with File Server Middleware.
Now let's have a look at How to Customize these Middlewares:

How to Customize Middleware ???

  • We have discussed it in Middleware lecture that each Middleware starts with "Use" keyword and they are all extension methods.
  • Now, in order to Customize these Middleware objects, we need to use respective Options Objects.
  • So, let's change the default homepage file to any other file, here's the code:
  • After the Routing Middleware, I have created a new instance of File Server Options.
  • You can see that, it has the Middleware Name i.e. File Server & then "Options" keyword.
  • Similarly, for Default Files Middleware, we have DefaultFilesOptions object for customization.
  • After creating the new instance, I have cleared the default file name first and then added a new file name "tep.html".
  • You must have created this HTML file in your wwwroot folder, so that File Server Middleware could access it.
  • Finally, I have provided this fileServerOptions object as a parameter to UseFileServer Middleware.
  • So, that's how we can Customize our home page as well as middleware.
  • So, key point to note here is: Middleware starts with "Use" keyword, while its customizing object ends with "Options" keyword.
So, that was all about How to handle Static Files in ASP.NET Core. In the next lecture, we will have a look at this Developer Exception Page Middleware, present at the start of our request processing pipeline. Till then take care & have fun !!!

Middleware in ASP.NET Core

Hello friends, I hope you all are doing great. In today's tutorial, we are going to have a look at what are Middleware in ASP.NET Core. It's our 3rd tutorial in ASP.NET Core series. In order to understand the Middleware, we have to open the Startup.cs file present in Solution Explorer. In our previous lecture, we have discussed the Code in Startup.cs and I have told you thhat we will discuss the Configure method later, so now we have to understand that code first. So, first let's define middleware components and then have a look at that code:

Middleware in ASP.NET Core

  • Middleware in ASP.NET Core are simple software components used to control HTTP requests and handle both incoming requests as well as outgoing responses.
  • Each middleware is a separate object, has a specific role assigned to it and are placed one after another in the request processing pipeline, as shown in below figure:
  • The middleware components are used for different purposes i.e. Authentication, Logging in, Verification, File Upload ( .js, .css ) etc.
  • These middleware components operate in fix order from top to bottom, so the incoming request is first received by the 1st Middleware and after proper processing on the request, it is forwarded to the 2nd Middleware.
  • A middleware can also skip the request and without any processing, forward it to next middleware.
  • For a proper working cloud based web application, we have to add a lot of middleware components, which we will see in coming lectures.
  • There are many builtin middleware components available in ASP.NET Core as Nuget packages and we can also design custom middleware components in it.
  • So, now let's open the Startup.cs file and have a look at the Configure Method, as shown in below figure:
  • You can see in the above code that we have a Startup Class, which has two functions in it, which we have discussed in our previous tutorial.
  • So, now let's have a close look at the code in Configure Method, it currently has three middleware components in it.
  • The first middleware components is placed inside IF loop and is shown in figure on right side.
  • You can see in the IF Loop we have Developer Exception Page, it's a builtin ASP.NET Core Middleware Component.
  • By convention, each middleware component start with "Use" word in ASP.NET Core, so if you are designing a custom middleware component, then its better to follow this practise.
  • We will study this Developer Exception Page in detail later, but for now you just need to know that its a middle ware component which shows an exception page to the developer and as it's inside IF Loop so it will be available only in Developers Environment, we will study Environment in coming lectures.
  • One more thing, we are using app and then dot operator to use Middleware in ASP.NET Core.
  • Second Middleware Component is app.UseRouting(), so the middleware name is Routing.
  • Finally the third middleware is End Points, which is displaying Hello World! on the page.
  • These Middlewares in the Configure Method, collectively create a pipeline structure i.e. there are executing one after another from top to bottom, this pipeline structure is called Request Processing Pipeline.
So, that was all about Middleware in ASP.NET Core. If you got into any trouble, then ask in comments and I will help you out. In the next article, we will have a look at How to add static files in ASP.NET Core. Till then take care & have fun !!!

Create First Web Application in ASP.NET Core

Hello friends, I hope you all are having fun. In today's tutorial, we will create our First Web Application in ASP.NET Core. It's our 2nd tutorial in ASP.NET Core series and in our previous tutorial, we have had a detailed Introduction to ASP.NET Core. We have also installed Microsoft Visual Studio Community Edition 2019 in our previous tutorial and today we will create our first web application in it. After creating this web application, we will also have a look at its files and will understand the contents. So, let's create our First Web Application in ASP.NET Core:

Creating Web Application in ASP.NET Core

  • First of all, start your Visual Studio which we have installed in previous tutorial.
  • A pop up window will open up, where you can open your recent project or can create a new project, as shown in below figure:
  • Here, click on the button says "Create a new project" and a new window will open up.
  • This new window will ask for the type of application, you want to create i.e. Console App, Web App, Blazer App etc.
  • As we want to create an ASP.NET Core Web Application so, I am going to select 3rd option in the list, as shown in below figure:
  • After selecting ASP.NET Core Web Application, now click on the Next Button.
  • On the next window, we have to provide the name & location for the project, as shown in below figure:
  • Now click on the Create Button and in the next window, we need to select the template for your web application.
  • Rite now, we are going to select the Empty Project, as I want to start from the scratch but in our incoming tutorials, we will cover almost all these templates.
  • You will also need to uncheck the check box says "Configure for HTTPS", as shown in below figure:
  • So, select the Empty Template for your ASP.NET Core web application and click the Create Button.
  • As you can see at the top of above figure that we are using ASP.NET Core 3.1 that's the latest stable .NET framework SDK.
  • When you click on the Create Button, Visual Studio will create your web application, as shown in below figure:
  • As we have selected the Empty template, that's why we don't have much files in the solution explorer and this web app won't do anything except printing " Hello World " on execution.
  • In order to execute our first web application, we need to click on the IIS Express play button, at the top menu bar.
  • Our default browser will open up and Hello World will be printed in it, as shown in below figure:
  • The link of this page is localhost:51640, as its on localhost rite now and the its port is 51640.
  • We will discuss the flow of How this web app works and what's IIS Express in our coming lectures.
So, rite now we have a simple working web application in ASP.NET MVC which simply prints Hello World. Now let's understand the files automatically created by Visual Studio in Empty Template:

ASP.NET Core Project File

  • If we have a look at the Solution Explorer, the we can see that visual studio has created few files for us, as shown in below figure:
  • In order to open the project file, we have to right click on the Project's name and then click on Edit Project File.
  • A new code file will open up with an extension .csproj, cs stands for C# & proj for project. This file is called the ASP.NET Core Project File.
  • In previous versions of ASP.NET, we have to unload our project in order to open this project file but in Core, we can simply click on this Edit option to open Project File.
  • If programming language is visual basic, then extension of project file will be .vbproj, vb for visual basic & proj for project.
  • The only element we have in our web application's project file is Target Framework and the value we have set is netcoreapp3.1.
  • This element, as the name implies, decides the target framework for our app and if you remember, while creating this project, we have selected .NET Core Framework 3.1.
  • This value inside Target Framework tag is called Target Framework Moniker (TFM ), so the TFM of .NET Core 3.1 is netcoreapp3.1.

ASP.NET Core Program File

  • Next file we are gonna open is Program.cs, its a C# class file, thus has an extension of .cs.
  • Now let's have a look at its code:
  • As you can see in above code that we have a class named Program and inside this class we have our Main Method.
  • This Main Method is the entry point of our compiler i.e. when our web App executed then this Main method is called.
  • If you have worked on any previous versions of .NET framework, then you must have seen this Main method there as well, in fact this web App executes as a console application.
  • Within this Main Method, we have called CreateHostBuilder Method, its implemented below Main Method and returns an object that implements IHostBuilder.
  • We are passing command line arguments to this CreateHostBuilder Method and then building our web host, which is going to host our web application and finally we are running our web app.
  • If we have a look at the CreateHostBuilder Method, then you can see that we are using webBuilder Method and then calling the extension Method Startup.
  • This WebBuilder Method is responsible for creating the web host on which our web app is going to host.
  • This Startup extension method is available in our next file named Startup.cs, so let's discuss it's code:

ASP.NET Core Startup File

  • Below Program File, we have Startup.cs file in our Solution Explorer.
  • So, let's open this file and here's its code:
  • This Startup Class is called by the CreateHostBuilder Method in Program File.
  • Inside this Startup class we have two methods, ConfigureServices & Configure.
  • ConfigureServices Method is used for the configuration of services, required for our web application.
  • Configure Method is used to configure the request processing pipeline for our web application.
  • This method has Hello World in it, which is actually printing on the page, we will discuss this method in coming tutorials in detail.

ASP.NET Core launchSettings,json File

  • launchSettings.json file is placed inside Properties, so open this file.
  • This file is only required for development purposes on the local machine, when we are publishing our web App then we don't need this file.
  • This file actually contain the settings for the hosting environment, as shown in below figure:
  • You can see in above code that first we have iiSettings and then profiles.
  • In profiles, we have two profiles named IIS Express & TheEngineeringProjects, which is also the name of our project.
  • When we run our project from visual studio, then this IIS Express profile is called and if you remember, the port number was same as in iisSettings i.e. 51640.
  • But if you run this app from Console, then TheEngineeringProjects profile will be called and in that case port number will be 5000.

ASP.NET Core appSettings.json File

  • That's the settings file for ASP.NET Core web application.
  • We use this file to store some hard coded values or settings etc., we will discuss it in detail later.
So, that was all for today. I hope you have completely understood the basic structure of our ASP.NET Core web application. In the next tutorial, we will have a look at Middleware in ASP.NET Core. Till then take care & have fun !!!

Introduction to ASP.NET Core

Hello everyone, I hope you all are doing great. Today, I am going to start this new series on ASP.NET Core and it's our first tutorial in this series. I will start from basics and will slowly move towards complex concepts. So, if you haven't worked on ASP.NET then you don't need to worry about that but you must have some basic knowledge of C# and object oriented programming. I will use Visual Studio 2019 for these tutorials, it's community version is free to use and I will use C# language for developing ASP.NET Core web applications. So, let's first have a look at what is ASP.NET Core:

Introduction to ASP.NET Core

  • ASP.NET Core (originally deemed as ASP.NET xNext & was going to named as ASP.NET 5) is an open source, modular, cross platform and high performance Framework used to build advanced cloud based Internet Applications i.e.
    • Web Application.
    • Android Application.
    • IOS Application.
  • It's built ( rewrite ) completely from scratch by Microsoft & its vast community (as its open source) and combines ASP.NET MVC & ASP.NET Web API in a single package, which were previously available as separate entities.
  • Although Core is a completely new framework but still it has quite a lot of resemblance with ASP.NET so if you have already worked on ASP.NET then Core won't be that difficult for you.
  • As ASP.NET Core is an open source framework, so you can download or update its code from respective repositories on Github.

Why use ASP.NET Core ?

Let's have a look at few benefits of using ASP.NET Core:
1. Cross Platform
  • The first & foremost advantage of ASP.NET Core is Cross Platform accessibility. In ASP.NET, you can only host your application on Windows platform but that's not the case with ASP.NET Core, you can host its applications across different platforms i.e.
    • Linux.
    • Windows.
    • macOS.
    • UBuntu.
    • Or any self host server.
2. Unified Programming Model
  • ASP.NET Core follows Unified Programming Model, that's why both MVC & API Controller classes inherit from single Controller base class, which returns IActionResult.
  • IActionResult, as the name implies, is an Interface and has a lot of implementations and two of most commonly used are:
    • JsonResult.
    • ViewResult.
  • In case of Web Apis, we get JsonResult and in case of Web MVC we can get both of them.
  • In previous versions of ASP.NET, we have separate Controller classes for Web MVC & Web API.
3. Dependency Injection
  • ASP.NET Core also has builtin support for dependency Injection, which makes it too flexible and conventional to use.
  • Normally we use class constructors to inject dependencies and is called Constructor Injection.
  • We will cover them in detail in upcoming tutorials, so if you are not getting this stuff then no need to worry.
4. Modular Framework
  • ASP.NET Core also follows modular framework and uses middle-ware components which makes the flow of the app smooth.
  • Microsoft has provided a lot of built-in middle-ware components for different purposes i.e. authentication, verification, File Fetching etc.
  • We can also create custom middle-ware components as well in AP.NET Core.
5. Open Source
  • ASP.NET Core is an open source framework and thus has a vast community on GitHub and Forum etc., that's why it's evolving rapidly and has become extremely powerful.
  • You can get detailed and instant help on Core online quite easily.
6. Development Environment
  • We can use Microsoft Visual Studio or Microsoft Visual Code for building our ASP.NET Core Applications.
  • We can also use third party editors i.e. sublime etc. for ASP.NET Core.

Prior Knowledge Required for this Course

  • If you haven't studied ASP.NET then no need to worry as we are gonna start from scratch and will cover all concepts.
  • But you must have good understanding of C# concepts, so if you are not that good in C# then you should first read this C# Tutorial.
  • Similarly, you should also have some basic knowledge of Html, CSS, Javascript, Jquery, XML etc. These are all simple languages so you must first their basic tutorials as well.

Setting up Environment for ASP.NET MVC

  • We can use any Integrated Development Environment (IDE) for ASP.NET MVC i.e. visual studio, visual code, sublime, atom etc.
  • We will also need to install .NET Core SDK, which is a software development kit.
  • Microsoft Visual Studio Community Edition is free to use and you can download it from its official website.
  • Once you downloaded a simple setup of around 1.5MB, you need to run that .exe file and it will start downloading the setup files, as shown in figure on right side.
  • Once it's downloaded all the required files to start the setup, a new window will open up as shown in below figure:
  • That's called workload area of Visual Studio, here you need to select which tools, you want to install on your machine.
  • I am going to select these 3 options from this list:
  • As of this tutorial, the latest version available is Microsoft Visual Studio Community Edition 2019 and .NET Framework version is 4.7.2 (latest stable version), which will be automatically installed along with visual studio.
  • If you are using any third party editor i.e. sublime, then you need to download the .NET Core SDK and install it on your machine.
  • .NET Core SDK is available for Windows, Linux, macOS and Docker.
So, that was for today. I hope you have enjoyed today's tutorial and are ready to get your hands dirty with ASP.NET Core. In our next tutorial, we will create our first project in ASP.NET Core and will write some code. Till then take care & have fun !!!

NuGet Package Management in ASP.NET MVC

Hello friends, I hope you all are doing great and having fun with your lives. In today's tutorial, we will discuss in detail about NuGet Package Management in ASP.NET MVC. It's 15th tutorial in ASP.NET MVC series. Today's tutorial is not about programming, instead we are gonna discuss this pre installed tool NuGet Package Management in ASP.NET MVC. NuGet Package Management is use to install packages and libraries, which you want to use in your project. It downloads the files online and then installs it. So, let's discuss this ASP.NET MVC tool in detail:

NuGet Package Management in ASP.NET MVC

  • NuGet Package Management is a package manager for ASP.NET MVC, which is used for downloading and installing different packages & Libraries online.
  • If any of your packages needs to be updated, then it can also be done by NuGet Package Management.
  • There are many third part packages available online, even there are many independent packages developed by Microsoft itself, which you can easily download & install using NuGet Package.
  • These third party packages could be open source or closed source.
  • So, now let's have a look at How to install any package using NuGet Package Management in ASP.NET MVC.
  • Right Click on your Projects' name in Solution Explorer and then click on Manage NuGet Packages, as shown in below figure:
  • It will open up a NuGet window in your workspace, as shown in below figure:
  • You can see in above figure that NuGet window is opened and it has three tabs:
    • Browse: For browsing new packages.
    • Installed: Search pre-installed packages in your visual studio.
    • Updates: Here you will get the notifications for updates of your pre-installed packages.
  • On the right side of each package, we have two versions listed.
  • The upper version is the installed version of that package in your visual studio software and the lower one is currently available version.
  • You can click on the upper arrow to update that package.
  • Here's the video demonstration of NuGet Package Management in ASP.NET MVC:
So, that was all about NuGet Package Management in ASP.NET MVC. It was a quick tutorial as I don't have much to explain here, its a simple tool but you should know about it as it will be used in coming tutorial. That's why I have posted it. If you have any questions, please ask in comments and I will try my best to help you out. Thanks for reading, have a good day. Take care !!! :)
Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir