How to include Bootstrap 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 include & use Bootstrap in ASP.NET Core. It's our 12th tutorial in ASP.NET Core series. As it's ASP.NET Core tutorial so I am not going to explain bootstrap much. But you must have the basic idea of Bootstrap, its a client side package of CSS libraries, designed by twitter and these days you can't design a responsive site with Bootstrap as it follows symmetry and is too easy to use. So, let's get started with How to include Bootstrap in ASP.NET Core:

How to include Bootstrap in ASP.NET Core

  • There are many third party tools ( Bower, NPM, WebPack etc. ) available in Visual Studio for installing client side applications like Bootstrap, JavaScript, Jquery etc.
  • But we are going to use builtin tool of Visual Studio called LibMan ( short for Library Manager ), for installing third party packages, we can use both file system & CDN.
  • LibMan is a light-weight client side library acquisition tool, which not only downloads the third party libraries but also keep a track in a special file.
  • In order to open Library manager, right click on your project's name in Solution Explorer & then Add > Client Side Library and below dialog box will open up:
  • You can see in above figure that I have made a search for twitter-bootstrap@4.3.1 in the Library Text Box and LibMan previewed its files.
  • After that I have changed the Target Location and its now wwwroot/lib/bootstrap, so my bootstrap files will be placed inside lib folder of wwwroot folder.
  • After these settings click the Install button and these bootstrap files will be installed.
  • Let's also install jquery using Library manager, as shown in below figure:
  • Library Manager has also created LibMan.json file which keeps the record of all the third party packages installation.
  • I have placed both bootstrap & jquery in wwwroot > lib folder, as shown in below figure:
  • That's how, we can easily install third party client side packages in ASP.NET Core.
  • Now, we need to include this Bootstrap file in our Razor Layout View file, as shown in below figure:
  • You can simply drag & drop the bootstrap file in this Layout file and the link tag will automatically be generated.
  • So, now let's add some bootstrap code in our Info View file to make it look eye caching, as shown in below figure:
  • Now run your application and navigate to info page and if everything goes fine then you will get similar results, as shown in below figure:
  • Now you can see our page got a much nicer look with bootstrap included.
So, that was all about bootstrap in ASP.NET Core. I hope you have enjoyed today's lecture. In the next tutorial, we will have a look at Tag Helpers in ASP.NET Core. Till then take care & have fun !!!

URL Routing in ASP.NET Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at URL Routing in ASP.NET Core. It's our 11th tutorial in ASP.NET Core series and it's an important but quite easy concept to understand. You must be wondering how we are routing rite now as we haven't added any routing codes yet. But if you remember, we have used MVC with default route middleware in our pipeline and this middleware automatically sets up this default URL routing for our web application.  So, let's understand how this URL Routing works in ASP.NET Core:

URL Routing in ASP.NET Core

  • URL Routing in ASP.NET Core is used to provide the controller's action method to the incoming HTTP request.
  • In simple words, when a user enters an HTTP URL in its browser, then it is greeted by the respective controller's method and which controller's method should by executed, it is decided by the URL Routing.
  • As you can see in below figure that our controller class has two action methods in it i.e. Index & info:
  • By default, first segment of URL ( home in our case ) is the name of the Controller and the second segment is the name of the action method. So, when we have info in the second segment then Info action method will be executed.
  • So, now let's understand this third segment in URL link, which is routed as a parameter to the action method.
  • If you remember, when we created the Info action method then we have hard coded the value of Engineers to 1.
  • So, let's make it flexible and ask the user to enter it as a third segment in the URL.
  • Open your Controller's file and make these changes to Info action method, as shown in figure on right side.
  • I have added a parameter int id in our Info method and then placed this id in the GetEngineers function.
  • So, now run your function and navigate to /home/info/3 and now you will get the data of your third engineer, as shown in below figure:
  • Now, we have automated our Info method by adding this third parameter and we can view any engineer's data quite easily.
  • But, if you open /home/info/ without the third parameter, then you will get a run time error and one way to avoid it is by making this third parameter null-able, as shown in figure on right side.
  • I have made the id null-able and then assigned it a default value of 1 by using id??1.
  • So, now if you don't add the third parameter then it will show you the data of first engineer by default.
  • This default routing of ASP.NET Core is also called Conventional Routing.
I hope you have understood the Conventional URL Routing in ASP.NET Core, so that was all for today. In the next lecture, we will have a look at How to include Bootstrap in ASP.NET Core. Till then take care & have fun !!!

Razor Layout Views in ASP.NET Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at different Razor Layout Views in ASP.NET Core. It's our 10th tutorial in ASP.NET Core series. You must have noticed in websites that they have common sections, which remains the same throughout the website i.e. Header Section, Footer Section, Sidebar etc. In today's lecture, we will have a look at how to design these default layouts of a website. We have already discussed the MVC architecture in detail so now it's time to start building our site's layout or basic structure. Today we will just discuss different files available in ASP.NET Core for default layout designing. So, let's get started with Layout View in ASP.NET Core:

Razor Layout View in ASP.NET Core

  • Razor Layout View in ASP.NET Core is a Razor file ( extension .cshtml ), used to design default Layouts of the website, which are then embedded in all ( or desired ) Views of the website.
  • A simple website's layout is shown in the figure on right side and these are normal sections of a blog and depending on site, these sections may increase or decrease.
  • Moreover, you may have more than 1 Layout for a single View i.e. different layouts for signed in users and guest users.
  • We place these Layout Views in Shared sub folder of Views folder, so let's create this Shared Folder inside Views folder and then click on Add > New item.
  • Add New Item dialog box will open up, make a search for razor in it, as shown in below figure:
  • We have already used Razor View to create Info View Page and we have seen that in razor files, we can use both html and C#, these are like smart HTML Pages.
  • So, today we will have a look at remaining Razor files and first let's add this Razor Layout file in our Views > Shared folder.
  • You must have noticed the underline sign ( _ ) before Layout name, its a convention ( not necessary ) to differentiate Layout files from other files, although you can write any name you want.

Why use Razor Layout View ?

  • It reduces repetition of code thus saves time especially in bigger projects.
  • Let's say you are working on a blog then you have to place these Footers, Headers & Sidebars etc and if you hard code them in each of your page then editing will be a serious issue.
  • That's why it's better to have all the default settings of our Views in a single file, so that we could change them easily.
  • Layouts are also used for consistent look and behavior of the website across all its webpages, you can think of them as HTML theme of your web application.
  • These Layout files are the alternative of Master Pages in ASP.NET Web Forms.
So, let's add some code in our newly created Layout View File:

Adding code in Razor Layout View file

  • We have added the Razor Layout file in our Views > Shared folder, open this file and you will find HTML code in it, as shown in the figure on right side.
  • As you can see this code is kind of an HTML wrapper having all the required tags i.e. head, body, meta, title etc. but it doesn't have any content in it.
  • It has 2 C# code lines in it:
    • First one is Title property which will set the title of the page.
    • Second one is RenderBody() method, View specific content will be injected here.
  • Both of these C# lines will be getting data from the View, which will be calling this razor layout.
  • Now, let's open our Info View file, and delete the wrapping HTML code, as shown in figure on right side.
  • Now, I just have the content HTML code in my Info View file.
  • Now let's enable this Info View file to use Razor Layout file and for that we have to include a new razor code block in our View file.

Layout Property in Razor View file

  • You can see in figure on right side that I have added a new razor code block at the top of my Info View File.
  • In this razor code block, I have specified two properties:
    • First one is the Layout property, where I have provided the path to the Razor Layout File.
    • Second one is ViewBag.Title, which was also present in Layout file and this property will set the Title of the Page.
  • Now run your web application and obviously you won't find any difference and if you check the Page soruce of Info page then you will find the complete html code in it with all required tags i.e. head, body, title etc.
Now let's have a look at another property called Sections in Razor Layout Files:

Render Sections in Razor Layout Files

  • Sections is a property in Razor Layout Files, which is used for the organized placement of few page elements.
  • You must have seen any movie review site, normally in such reviews, the review box is placed right at the top in either left or right corner displaying the overall review aggregate.
  • Sections are used to place such sticky elements in web pages, I have placed a Render section in my _Layout.cshtml file named AdBanner.
  • First I have placed an IF loop to check if the section is present in the View or not and if it's present then execute that section.
  • This IF statement is necessary as it makes the section optional otherwise it will be mandatory and if you don't have it in your View file then you will get a run time error.
  • So, this Ad Banner section will be placed at the end of the webpage.
  • Now, we need to create this AdBanner section in our Info View File, so open your View file and place the code as shown in figure on right side.
  • You can see I have used @section directive and then provided it the same name as in our Layout file and then in curly brackets { } placed the content ( which doesn't make much sense for now ).
  • Now run your project and open this link home/info and if everything goes fine then you will see this line at the end of your file, as shown in below figure:
  • So, despite the fact that we have placed the section at the top of our Razor View File but still it appeared at the bottom, as specified in the Razor Layout File.
  • We can create as many sections as we want in our Razor Layout file.
You must have noticed that we have to add the path of our Layout file in every View file, which is clearly a negation of DRY ( Don't Repeat Yourself ). So, let's see How to get rid of this linking.

Razor View Start File in ASP.NET Core

  • Razor View Start File in ASP.NET Core is used to specify the Razor Layout file location for Razor View Files.
  • It is normally placed inside the Views folder, so let's Add New item and in the search dialog box, make a search for razor, as shown in belwo figure:
  • Previously, we have selected Razor Layout file and this time we are going to select Razor View Start file and you can see it also has underscore sign ( _ ) at the start of the name.
  • Add this file to your project and you will find a simple code in it, as shown in figure on right side.
  • This code is automatically generated by visual studio, as it knows we have the Layout file in our project, so now we have successfully specified the Layout file for our View files.
  • So, now remove your path from the Info View file and run your project and it will still work the same.
  • It's really helpful as if you wanna change the name or path of your Layout file then you can quite easily do it here and it will be applicable to your entire application.
  • Moreover, Razor View Start file is hierarchical i.e. you can add View Start files in each folder and it will override the parent View Start settings.
  • So, if you wanna assign different Layouts to different Controllers then you can easily do that by adding a new View Start file in these folders.
  • We can still specify path to Layout file directly in View file and it will override everything, we can also make Layout = "null", which will remove all the Layouts from that View.
  • So, the Razor View Start file reduces the code redundancy and thus increases maintainability.
Finally, let's have a look at the Razor View Imports file, which is the last one in razor files import section:

Razor View Imports in ASP.NET Core

  • Razor View Imports in ASP.NET Core are used to include common namespaces, required by the Razor View files.
  • In our Info View file, you have seen that we have specified @model directive at the top and then provided fully qualified name of our View Model, which in our case is:

TheEngineeringProjects.ViewModels.HomeInfoViewModel

  • So, if we have to add more View Models or simple Models then we have to write full name again, which is again a violation of DRY, so it's always a better approach to place most commonly used namespaces in our Razor View Imports file.
  • This file is placed inside Views folder and is hierarchical ( similar to View Starts ).
  • So, right click on Views folder and then Add > New Item and select Razor View Imports file, it's name also starts with underscore sign ( _ ).
  • Inside this file, place this single line of code, as shown in the figure on right side.
  • Here, I have placed @using directive and then specified the namespace if my ViewModels folder and it will be automatically included in my View files.
  • So, now open your Info View File and remove this namespace from @model directive and now we will just specify the name of the ViewModel, which we are using for the View, as shown in below figure:
  • So, that's our final Info View Code and you can see that now we don't have any code repeatability in it.
  • The code is clean and contains only the content of this View file, so our project is more organized and maintained, although have no effect on the output.
So, that was all for today. I hope you have enjoyed today's lecture, it was quite a lengthy one but you must have got the idea how important it is. In the next lecture, we will have a look at Routing in ASP.NET Core. Till then take care & have fun !!!

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 !!!
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