Tuesday, September 24, 2019

EF Core joining tables using Include and selecting specific columns

In the previous posts we saw on how to join tables using Include and how to select specific columns form a table. In this post we will try to combine both of them, we will join tables using Include and select specific columns from the joined tables.

We will join the Employee table with Department and Country tables, select specific columns from each of the table and populate the below Model class.

EF Core select specific columns in a table

In the previous posts for CRUD operations we saw on how to select all the column values from a context table, sometimes we will not need all the columns from a table instead we will need only specific columns from a table. In these cases we can use a Select () clause to filter specific columns from a table. In this post we shall see on how to select only the Id, Name and Age properties from the employee table.

The employee table has the following columns. 

Sunday, September 8, 2019

EF Core Joining tables with Include

In the previous pose we saw on how to join tables using the join keyword. Entity Framework core also provides an alternate way to join tables using the Include clause.  To use include for joining the tables we need to set the Primary Key, Foreign Key relation in the Database. 

In the sample we have an Employee table which has a Foreign Key DepartmentId referencing to the Department table. We will join these tables using Entity Framework Core.

Saturday, September 7, 2019

Asp.Net EF Core Joining multiple tables

In the previous post we creates a custom model class EmployeeDetail, in this post we shall see on how to use Entity Framework Core to JOIN the Employee, Department and Country tables and populate data into the custom Model class EmployeeDetail.

We have 3 tables, the Employee table is the main table which has related data in the Department and Country tables, DepartmentId and CountryId are the Foreign Keys in the employee table.

Custom Models in Asp.Net Core

So far we have seen CRUD operations using a single table, in real time scenarios we will have to deal with data from multiple tables, like joining multiple tables and returning specific columns from each of the tables. The default Models created using Entity Framework Core will not help in these cases.

For example let us consider the following Employee table, which has references to Department and Country tables.

Saturday, August 24, 2019

Entity Framework Core GROUP BY (Grouping)

In the previous posts we saw on how to get data from a SQL Server table using EF Core context, how to filter data using various types of filters and how to Sort the data using sorting keys. In this post we shall see on how to perform Aggregate operations like COUNT, MAX, MIN etc by Grouping rows based on keys. This is similar to the GROUP BY clause in SQL Server.

Let’s start with a GROUP BY query which will get the count of employees in each of the City in the Employee table.

Entity Framework Core ORDER BY (Sorting)

In this post we shall see on how to sort the results from a table using LINQ Query, this is similar to the ORDER BY clause in SQL Server. In EF Core LINQ queries we can achieve this by using OrderBy.

Let us get the list of Employees in the Employee table sorted by the Name of the employee, this can be done using the following LINQ query.

Friday, August 23, 2019

Entity Framework Core sub-query (Filter rows based on results from another table)

In the previous post we saw on how to implement different types of row filters using LINQ queries, like Contains, StartsWith, EndsWith etc. In this post we shall see a more complex type of filter where the rows from the Employee table are filtered based on a specific type of Department Name.

We want to get the list of employees who belong to a Department whose name contains the word Account. In SQL server we can do this using a sub-query as follows.

Entity Framework Core Where clause (Filter rows based on conditions)

To filter a table for specific rows we need to use Where clause and specify a filter condition in the Where clause.

To get all employees who have Age > 30 we need to use the following LINQ Query

Entity Framework Core Select one row from a Table

To select a specific row from a table, we need to use the Select clause and pass the id of the row to be obtained. Let us say we want to get the Employee with EmployeeId = 1 from the employee table then the EF Core query will be as follows.

            var Employee = _context.Employee.Select(e => e.EmployeeId == 1);

Thursday, August 22, 2019

Entity Framework Core Select all rows from a Table

Selecting all the rows from a table is very simple, assuming that we have setup the Entity Framework Core context and generated all the Models we can use the context object to select all the rows from the Employee tables as follows.

List_context.Employee.ToList();


If we want to get all the Employees in a MVC Controller then the controller will be as follows

Entity Framework Core LINQ Queries

 Asp.Net Core uses Entity Framework Core to perform database operations like SELECT, INSERT, UPDATE and DELETE. Also SELECT involves various types like selecting specific columns, selecting specific rows, ordering rows, grouping rows, etc. In the following posts we shall see on how to perform various types of LINQ queries to achieve these requirements.

To perform LINQ queries we need an underlying SQL table and some data, for these sample we shall use the following tables and data. In the following posts we will use these table to perform different types of operations list SELECT, JOIN, WHERE, INSERT, UPDATE etc

Saturday, August 17, 2019

Asp.Net Core Web API Attribute Routing with Parameters

We saw on how to define custom attribute routing for Asp.Net Core WebAPI action methods and how to access the action methods using the custom Route. In this post we shall move a step further and see on how to use custom routes to pass parameters to the action methods.

Let us create one more action method to the Department controller which accepts an id parameter in the route.

Attribute Routing in Asp.Net Core Web API

In the previous posts we saw on how to use the HTTP verbs GET, POST, PUT & DELETE to invoke different action methods in an Asp.Net Core WebAPI controller, this approach holds good as long as we have only one Action method per verb in a controller, what if we want multiple methods with the same header or if we want to have custom routing to each action method, this is where attribute routing can help us. In this post we shall see on how to define custom routes to action methods using attribute routing.

Let us another controller DepartmentController, and add a Get method with a custom routing attribute as follows.

Wednesday, August 14, 2019

Creating a Delete method in Asp.Net Core WebAPI Controller

In this post we will create a HttpDelete method in Asp.Net Core WebAPI, which will be used to delete a row in the SQL Server database using Entity Framework Core. We have seen how to setup Entity Framework Core in an Asp.Net Core Web API project in the previous posts, in this post we will jump into creating the HttpDelete method.

Open the Country controller which we used in the previous post and add the following Delete method which uses the HttpDelete verb.

Creating a PUT (Update) method in Asp.Net Core WebAPI Controller

In this post we will create a HttpPut method in Asp.Net Core WebAPI, which will be used to update a row in the SQL Server database using Entity Framework Core. We have seen how to setup Entity Framework Core in an Asp.Net Core Web API project in the previous posts, in this post we will jump into creating the HttpPut method.

Open the Country controller which we used in the previous post and add the following Update method which uses the HttpPut verb.

Tuesday, August 13, 2019

Creating a POST (Insert) method in Asp.Net Core API Controller

In the previous post we created an API Controller and created a GET method, in this post we will create a POST method which will use Entity Framework Core to insert values to the database. We will use the same country controller and add a Create method.

Open the CountryController and add the following Create method, the method will take an object of type Country and insert the same to the Database.

Saturday, August 10, 2019

Asp.Net Core API Controller with a GET Method

In the previous post we added Entity Framework Core context to the Web API project, in this post we will use the EF context to get a list of values from the DB and expose the data in JSON format using a HttpGet method.

To start with we will have to add a reference of the DataAccess project which we created in the previous post to the WebAPI project. All database operations will be performed in the DataAccess project hence we will add a reference to this project.

Next in the WebAPI project we will add a new API Controller, name it CountryController

Adding Entity Framework Core to the WebAPI Project

In the previous post we saw on how to create a basic WebAPI project in Asp.Net Core using Visua Studio 2017. In this post we shall see on how to add Entitiy Framework Core support to the basic project. First let us create a class Library project with name DataAccess. This project will deal with all database interactions and we will implement EntityFramework Core in this project.

Once the DataAccess project is created, delete the default class1.cs which got created with the project. Add the following NuGet packages using the NuGet package Manager.

Saturday, July 27, 2019

Launch Settings in ASP.NET Core WebAPI

Asp.Net core applications contain a new settings file called launchSettings.json, this file is under the Properties menu. The file contains the settings for running the application in different environments.

By default an Asp.Net Core Web API project contains 2 settings. First one for running under IIS Express and the 2nd settings for running in command line.

Creating a HelloWorld WebAPI Project in Asp.Net Core

Open Visual Studio 2017
Create a new Project of type Asp.Net Core Web Application



Select the API template

What is Asp.Net Core WebAPI?

When Microsoft released Asp.Net Core MVC it also released the API version which is Asp.Net Core Web API. Asp.Net Core Web API is used to create restful services which can be used to create HTTP services which don’t have a View layer but have Controllers and Models, they process incoming requests and responds with data in JSON format.

Since Asp.Net Core Web API does not have a view layer, it also does not have the Razor view engine it returns the data in JSON format to other UI layer applications like Angular / Reach which will handle the UI rendering.

Thursday, May 30, 2019

Asp.Net Core MVC Model Binding and Validation

Model Validation Example in Asp.Net Core

In the previous post we saw on how to perform form field validations using Model State, in this post we will see an example of using Model Validations in a MVC Form. Following is the Model class with the validations.

Monday, May 27, 2019

Model Validation in Asp.Net Core

Validation is an important part of any application which accepts inputs from users, the data entered by the user needs to be validated for integrity before it is saved in the database. Validations could be on the type of data like int, string, decimal etc. On the format of the data like email, SSN, Phone Number etc. Also we might need custom validation specific to the application.

Asp.Net Core MVC Model validation provides us an easy and effective way to validate user input, using Model validation we can specify the validation parameters in the Model object and the framework will take care of validating the inputs in the View.

Model Binding in ASP.NET Core

Model Binding is the process by which the incoming parameters from a HTTP request are mapped to the parameters of the corresponding Action Methods. The parameters can be route parameters or parameters of the Action methods. Asp.Net core framework takes care of matching the parameters from the request with the route/action method parameters and populated the parameters automatically.

The Framework matched the HTTP parameters with the route/action method parameters using the parameter names, when a parameter name matches it populates the property value from the request and proceeds to match the next parameter.

Sunday, May 26, 2019

Asp.Net Core MVC Routing Overview

Attribute routing in Asp.Net Core MVC

In the previous post we saw about Routing in Asp.Net Core MVC Applications, and how to define Routing in the Applications Startup, this is called conventional routing. Asp.Net Core MVC applications also provide us another way to define routes called Attribute Routing.

Attribute Routing
As the name suggests Attribute Routing is defined by defining routes in action methods using a Route attribute as follows.

Defining multiple routes in Asp.Net Core MVC

In the previous post we saw about Routing in Asp.Net Core MVC Applications, also we saw different ways of defining simple routing. However for more complex application this simple routing might not be enough, we might have to define different routing paths for each module in the application like

/Accounts/. . .
/Contacts/. . .
/Reports/. . .

In this post we shall see on how to define multiple routing paths in Asp.Net Core MVC.

Remember we defined a simple routing which by default was pointing to Home/Index, let us extend this by adding 2 more paths to this routing pointing to the Employee & Users controller, the route definition will be as follows.

What is Asp.Net Core MVC Routing

In traditional Asp.Net Web Forms we access a page using the pages URL like
http://localhost/index.aspx

But in Asp.Net MVC we don’t specify the page name or extension in the URL, instead we specify the Controllers action method in the URL and the controller takes care of rendering the corresponding view. Asp.Net Core MVC uses a routing Middleware to map the incoming request to the action method. Routes can be specified either in the startup or as attributes in the Controller / Action methods.

Wednesday, May 22, 2019

Injecting Service into Asp.Net Core View

In the previous posts we saw on how register a service Dependency Injection in the startup and inject the service to the MVC controller or Action method. In some cases we might need to inject a service directly into the View. A typical example is populating dropdown lists in the view.

If a view has dropdowns we cannot use the original Entity model since it will not contain the option values for the dropdown lists, in these cases we will create a custom View Model with will contain the properties from the entity model and additional lists to populate the dropdowns in the view. By injecting services to the view directly we can avoid this by injecting services directly to the view to populate the dropdown option values and continue using the entity model to display the model properties.

To inject a service directly to a view we need to use the @Inject directive. The syntax for the @Inject directive is as follows.

Injecting Service into Asp.Net Core Action Methods

In the previous post we saw on how to inject a service to the MVC controller. This might not be needed always, there are cases where we will need the service only for one action method in the controller. In this post we shall see on how to inject a service to one of the action methods in a controller.

The service and the service registration in the startup remains the same, instead of injecting the service in the controller’s constructor. When injecting the service in the action method we need to use the [FromServices] attribute.  We will inject the service in the action method as follows.

Injecting Service into Asp.Net Core Controllers

In the previous example we created an interface IUserService and a service class UserService. We also registered the service in the Asp.Net Core startup. In this post we will see on how to inject this service in the constructor of MVC controller and use it to populate the view. To start with let us create a new MVC controller and name it UserServiceController.

In the constructor of the Controller class we will pass a reference to the IUserService. Since we registered this interface with the service class in the startup, the Asp.Net runtime will inject an instance of the UserService class to the controller. Following is the code for the MVC controller.

Sunday, May 19, 2019

Registering Service using Asp.Net Core Dependency Injection

Asp.Net Core provides built in support for Dependency Injection, we can register classes in the Application startup and inject instances of these classes wherever required like controller, views or other classes.

ASP.NET Core provides a built-in service container IServiceProvider to register class dependency. Services are registered in the Startup using the ConfigureServices method.

In previous examples we used to connect to the Database directly from the Controller layer, however in larger applications it is recommended to use a Service / Repository layer to interact with the database. Let us create a simple service class which will do the database operations, we will register this service in the Startup and inject this service in the controller using Asp.Net Core Dependency Injection.

Dependency Injection in Asp.Net Core

Dependency Injection is a design pattern which helps eliminate dependency between various classes and modules in a larger application. Dependency Injection aims in creating dependent objects for a class outside the class and injecting them dynamically into the class, instead of instantiating the dependent classes inside the main class. By doing this Dependency Injection helps us develop Applications with better modularity and test-ability.

Asp.Net Core provides built in dependency injection support for applications, in previous versions of Asp.Net dependency injection was implemented using 3rd party libraries like StructureMap, Unity etc. ASP.NET Core provides a built-in service container, IServiceProvider. Services are registered in the app's Startup.ConfigureServices method.

In Asp.Net Core a dependent service is registered with the service container in the ConfigureServices method of the Startup class as follows.

Saturday, May 18, 2019

ViewModel, Partial Views and Layouts in Asp.Net Core

Entity Framework Core with Asp.Net MVC Core Getting Started

Layout in Asp.Net Core MVC Views

Every page on a website will have some common elements like Header, Logo, Menu, Navigation links etc. A layout helps to create a common view for these re-usable part of the page and use it in each page of the application.

A layout is also a view with .cshtml extension. The layout view defines the header, content area and the footer sections. In general re-usable content is placed in the header and footer sections, the content section varying content of the pages. The content section contains a statement @RenderBody(), which embeds the varying content of each page in the content section.

A typical layout view page looks like this.

Partial view with Model example in Asp.Net Core

In the previous post we saw a simple Partial View example, where a string from the partial view is displayed in the main view page. In this post we will improve this example to take a Model object and display the properties in the Model object.

When invoking a partial view from a main view, we can also pass a Model object to the partial view as follows. The properties in the passed model can be used in the HTML markup of the partial view.

Partial view example in Asp.Net Core

Partial views are views whose content gets embedded in other View pages, partial views are added to other views using the <partial> element or using @Html.Partial helper tags. In this post we shall see a simple example of how to create a partial view and embed it in the main view page.

Partial views are usually named with a _ character in from of the view name to differentiate between partial views and other views. The following line shows how a partial view is referenced inside other views.

Partial views in Asp.Net Core MVC Views

A Partial View is another view page with .cshtml extension, Partial Views are used to modularize larger view pages and also to re-use common functionality across different views in the application.

Partial views improve maintainability by breaking down a large view page into modular views and embedding the partial views in the main view template. By doing this the markup code in the main view page reduces there by improving readability and maintainability.

Partial views also help reduce duplication of code in larger applications, if we have a common functionality / display content which is to be repeated in many places the a large application, then we can place the repeating content in a partial view and just embed the partial view wherever required. This reduces duplication of same logic in many places. Also improves maintainability since any change to the common logic needs to be done in only one place, in the partial view.

The syntax for including partial views varies by the version of Asp.Net Core used, in Asp.Net Core 2.1 we use the partial tag to include partial views as follows.

Thursday, May 16, 2019

Displaying Bootstrap Model in an MVC View

In the previous posts we saw on how to create Asp.Net Core MVC Controllers and Views for CRUD operations. In this post let us add a little bit of styling. Let us create a bootstrap Model and display it on the click of a Bootstrap button.

We will add a bootstrap button and set its target to a Bootstrap model, below is the bootstrap button.

Creating a ViewModel object and bind it to the View

In the previous post we created a custom controller and we developed our own view and it worked. There is one think to note in that sample, the controller was passing a list of Employee object will all the properties, but the view was displaying only specific properties. Though this works it’s not efficient while displaying larger lists, we end up fetching way too much data from the database but not using it. To avoid this we have to create a custom ViewModel object with only properties used in the view. In this sample we will modify the previous example to use a ViewModel object.

First create another folder inside the Models folder, name it ViewModel we will create all our ViewModel objects inside this folder. Next create a class EmployeeSummary.cs in this folder as follows.

Sunday, May 12, 2019

Asp.Net Core MVC - Creating an Empty Controller and develop Manually

In the previous sample we saw on how to create a controller in Asp.Net core MVC using the using Template to create all Action Methods for CRUD operation, this was very easy since Visual Studio created us all the Action Methods by default. This is very handy when we want to do CRUD operations, however in some cases this might not come in very handy, we might want to create our own action methods, in such cases we will create an Empty controller without Action methods. In this post we shall see on how to create an Empty controller and build on top of it.

Open Visual Studio, create a simple MVC project as we saw in our previous posts. Once the project is up and running we will add our empty controller. Follow the below steps to create an empty controller.

Customize Validation error message in ASP.NET Core MVC

In the previous post we saw on how to implement field level validations by adding validation attributes to the Model class. We saw that the validation messages were auto generated based on the validation rules, we might want to add custom validation messages, we can do this by adding an ErrorMessage property to the validation attributes.

In the sample below we will add custom error messages using the ErrorMessage property and see how this is reflected in the View.

Adding Model Validations in ASP.NET Core MVC Views

In the previous posts we saw on how to create an Asp.Net Core MVC controller and views to View, Edit and Delete detail using Entity Framework Core. In this post we will see on how to add Model validations which will be applied to the Views to validate data before we Add/Delete details to the database.

Asp.Net Core makes it easy to validate entities, all we need to do is to add the validation properties to the Model class and Asp.Net Core takes care of applying the validations in the view automatically. In the previous version of Asp.Net MVC we had to validate the user input fields in the View layer using Validation controls like Required Field validator, Range Validator, Regular expression validator etc, but Asp.Net Core takes care of this for us.

Wednesday, March 27, 2019

Creating a Delete view using EF Core

In the previous posts we created a List, Details and Edit views using Asp.Net Core MVC and Entity Framework Core to connect to Database view and edit details from SQL Server DB. In this post we will see on how to create a Delete view which will display the details of an Entity object (User) and allow us to delete the User from the database.

Similar to Edit, the delete operation will use 2 action methods. A GET method to get and display user details and a POST method to delete the user from the DB.

Creating an Edit view and display data using EF Core

In the previous post we saw on how to create a Details view using Asp.Net Core MVC and Entity Framework Core and display the details of an users from the Users table in SQL Server database. In this post we will create an Edit view which will be used to edit the user details.

Remember we had an Edit action link in the list this view will be linked to the Edit link, on clicking the Edit link against a user will trigger the Edit action method in the controller which in turn will get the user details from the DB using Entity Framework Core and pass on the Model object to the View to render the user details in the browser, which can be edited and saved.

Edit and Save will use 2 different action methods a GET and A POST action method, the GET method will get the user details from the DB and the POST method will be used to save the details back to the DB.

Saturday, March 16, 2019

Creating a Detail view and display data using EF Core

In the previous post we saw on how to create a List view using Asp.Net Core MVC and Entity Framework Core and display a list of users from the Users table in SQL Server database. In this post we will create a Details view which will display the user details of a specific user.

Remember we had a Details action link in the list this view will be linked to the Details link, on clicking the Details link against a user will trigger the Details action method in the controller which in turn will get the user details from the DB using Entity Framework Core and pass on the Model object to the View to render the user details in the browser.

Creating a List view and display data using EF Core

In the previous post we created an MVC Controller for our Asp.Net Core application using Entity Framework core. In this post we shall create a List view which will display the list of users in the database fetched using. Let us start by adding a view to our Index action method. Entity Framework Core

Visual studio has already added code in the Index action method of the controller to fetch the list of users using Entity Framework Core.

Thursday, March 14, 2019

Creating a controller for CRUD operation using EF Core

In the previous post we saw on how to setup Entity Framework Core for out Asp.Net Core application. In this post we will use the EFCore and create a controller for CRUD operation. In this sample we will not do too many customization we will rather use the Built in Scaffolding from Visual Studio to create the controller.

In Visual Studio Right-click on the Controllers folder in Solution Explorer and select Add > Controller.

Setting up Entity Framework Core for MVC Database First Application

So far we have seen simple examples using Asp.Net MVC to display static messages and static list of model objects, however complex applications will have to deal with database display and update data from the database. In the previous versions of .Net / MVC we used Entity Framework to interact with the database with .Net Core we will use Entity Framework Core to interact with the database. In this post we shall see on how to set up EF core to interact with the database.

First step to setup EFCore is to create a Models folder, let us create a folder EFCoreModel in the project. Next we need to add the following 3 NuGet packages to the project we can do this either using Package Manager GUI or Package Manager console.

Thursday, March 7, 2019

Tag Helpers in ASP.NET Core

Tag Helpers were introduced in Asp.Net Core, Tag Helpers are similar to HTML Helpers but have improved syntax to look similar to HTML elements. Tag Helpers are attributes added to normal HTML elements to provide server-side processing ability.

Tag Helpers provide IntelliSense support in Visual Studio. There are many built-in Tag Helpers for common tasks such as creating Form, Input, Label, Hyperlink etc

Let us compare the HTML helpers with the new Tag Helpers for a text-box and see the syntax difference.

Tuesday, March 5, 2019

Passing data from Controller to View Examples

In the previous post we saw different ways in which we can pass data / objects from the controller to the View. In this post we will see a simple example on how to assign values in the controller and use them in the View using the different methods ViewData, ViewBag and TempData.

In the controller, we assign string and objects to the ViewData, ViewBag and TempData as follows.

Passing data from Controller to View

There are different ways to pass values / objects from a controller to a view in Asp.Net Core MVC. Following are some of the commonly used ways.

ViewData – Returns a ViewDataDictionary, allows us to store key-value pairs in the controller and access them in the view. The key is a case sensitive string and the value can be any type int/string/object etc. When we use ViewData to pass custom objects we need to cast them in the View before using the properties.

Monday, March 4, 2019

Binding Model to View and Display data

In the previous post we saw on how to create a Model class, in this post we will use the model class in the controller to populate the model properties and pass on a list of Model objects to the view layer to display the data in the view.

In the controller we will instantiate the model class set values to its properties and bind it with the view to display the data. Next let us edit the Home controller and initialize the model object as follows.

Adding Model class to Asp.Net Core MVC

In the previous post we saw a basic Hello Word sample for MVC application using Asp.Net core. Let us now do some more improvement to the example and add a Model class to the project. Model is a Domain object or Business object which contains properties to represent the object. For example Product is a model class which contains properties like ProductName, Number, Cost etc.

Model is one of the layers of the MVC architecture, in MVC model deals with the data / structure of the business objects. Model objects are populated in the controller and passed on to the View layer for display. Let us not add a Model class Product to the MVC project. To do this right click on Model folder -> Add -> click on Class. Let us name our class Product.cs. Add the following code to the Model class.

Friday, March 1, 2019

Asp.Net Core MVC Hello World Example

In the previous post we saw on how to setup a basic Asp.Net core MVC project using Visual studio. In this post we shall examine the various files and methods in the basic project. As a recap we used the following steps to create the basic MVC project.

o   Open Visual studio (I am using VS 2017) and select new Project.
o   Select Web -> .Net Core
o   Select Asp.Net Core web application
o   Provide a name (Hello MVC) and path and click OK
o   In the templates select Web Application (Model-View-Controller) and click OK
o   This will create a basic MVC project with one Controller and View

Now let us examine the files and methods in the project. Let us start with the Program.cs.
This file looks similar to the basic Asp.Net Core project file. It hooks up the host and starts up the application.

Setting up MVC in Asp.Net Core

We have so far seen samples of how to display Hello World text in the browser from Asp.Net core, rendering a static HTML page from Asp.Net core etc. Let us now move on a little further to setup MVC in the Asp.Net Core application. Follow the below steps to create a basic MVC project using Asp.Net Core

Ø  Open Visual studio (I am using VS 2017) and select new Project.
Ø  Select Web -> .Net Core
Ø  Select Asp.Net Core web application
Ø  Provide a name (Hello MVC) and path and click OK
Ø  In the templates select Web Application (Model-View-Controller) and click OK
Ø  This will create a basic MVC project with one Controller and View

The project structure looks like this.

Friday, February 22, 2019

Adding UseStaticFiles Middleware

The UseStaticFiles is another important middleware which is required to server static HTML, CSS or JavaScript files to the browser. In Asp.Net Core static files are placed in the wwwroot folder. In this example we shall start by adding an index.html file and serve this file to the browser using the UseStaticFiles middleware.

Let us start by adding a static HTML file to the Hello World sample, open the project and right click on the wwwroot folder Add -> New Item, in the list of file types select HTML file, give it a name index.html and create the file. Add some sample text to the file as follows.

Adding Configuration to Asp.Net Core

Configuration is another important aspect of any Application, in this post we shall see on how to add a configuration file and read the key/value pairs from the config file in the application. In traditional Asp.Net and MVC applications we had a default web.config file where we can add the config entries and use them in the application. Asp.Net core is different, here we use a JSON file for the configurations. In this post we will add a configuration file appsettings.json and read the config entries from the file at Startup.

Let us use the basic Hello World application and modify it slightly to add the configurations. First add a new JSON file to the application, name it appsettings.json. Let us add a config entry to the file as follows.

Monday, February 18, 2019

Adding UseDeveloperExceptionPage Middleware

Exception Handling is an integral part of any application, if exceptions are not handles we will see the system exception page like status code 500, this will not provide much information to the developers to investigate on the exception. In the previous .Net Framework MVC by default the stack trace and line information will be displayed in the browser, but in .Net core it shows a generic error message.

Sunday, February 17, 2019

Adding Middleware to Asp.Net Core

In the previous posts we saw a simple HelloWorld application which displays a message in the browser when the application runs. In this post we will further enhance the application by adding another Middleware to the execution sequence.

Hello World example in Asp.Net Core

In the previous posts we saw about what Asp.Net Core is, its features and its advantages. Let us get started with a simple Hello World example in Asp.Net Core. We will use Visual Studio for this example. We can use Visual Studio Code also for a simple example like this, but for complex example Visual Studio is a better tool, hence we will use Visual Studio for this example.

Before we begin the example make sure that .Net Core SDK is installed in the machine, also install Visual Studio. In this example we will use Visual Studio 2017. Let’s get started.

Sunday, February 10, 2019

Asp.Net Core Host and Logging Configuration

A simple Asp.Net core application contains a Startup.cs file and a Program.cs file. We saw that the Startup file is used to define the execution pipeline to process Http requests and to inject services. In this post we shall see about the role of Program.cs file.

The Program.cs file in an Asp.Net core application contains logic to define the host configuration and logging configuration. It has the public static void Main() method which is the entry point of the application.

The Main() method calls CreateWebHostBuilder, which in-turn calls WebHost.CreateDefaultBuilder, this method performs the following tasks under the hood.

Asp.Net Core Startup Configuration

Startup configuration for Asp.Net Core applications are defined in a startup file Startup.cs. This is similar to the global.aspx.cs file in the previous version of Asp.Net. Startup settings are important in Asp.Net Core since we need to define the execution pipeline during startup to handle all incoming requests.

There are 2 important methods in the Startup which define the execution sequence of Asp.Net core request execution.

Configure
ConfigureServices

Monday, February 4, 2019

Advantages of Asp.Net Core

Asp.Net core is a light weight, cross-platform compatible web development framework from Microsoft. Asp.Net core can be considered as the next generation web development framework from Microsoft, Asp.Net for long has been windows centric, for the first time Asp.Net core has made web application development possible in multiple platforms. The other key improvement in Asp.Net core is that it can produce light weight applications with higher performance compared to the previous version of Asp.Net. Let us look into some of the advantages of Asp.Net core in detail.

What is Asp.Net Core

Asp.Net core is a new web development framework from Microsoft providing cross platform compatibility. The previous version of Asp.Net could be developed in Windows and deployed in IIS. Asp.Net core changes this, Asp.Net core applications can be developed in Windows, Linux or Mac OS.

Asp.Net core also aims in producing leaner light weight applications compared to traditional Asp.Net applications. Asp.Net core provides more flexibility in the way we design our applications, it allows us to chain a set of Middle-ware's to process the Http request.

Each middle-ware performs a specific task and passes on the result to the next Middle-ware in the chain. Each piece of middle-ware in ASP.NET Core is an object, and each piece has a very specific, focused, and limited role.

Saturday, January 19, 2019

.Net Core Getting Started

.Net Core Overview

Hello World .Net Core console App with Visual Studio

In the previous posts we saw on how to create a .Net Core console app using command line and using Visual Studio Code. In this post we shall create a .Net Core console app using Visual Studio. To begin with open Visual Studio, select New Project and select the template .Net Core -> Console App.

Hello World .Net Core console App with Visual Studio Code

In the previous posts we saw on how to create a simple Hello World console application using the dotnet CLI tools. This is fine for simple applications, when we want to build complex applications with multiple files we need a good editor to view and switch between multiple files in the project.

Tuesday, January 8, 2019

Deploying .Net Core using command line tools

We saw that .Net Core offers 2 types of deployment framework-dependent deployment and self-contained deployment. In the post we shall see on how to deploy a simple console applications using the command line (CLI) tools.

Let us takes the simple Hello World console application, and try to create a deployment package for the application. 


Deploying .NET Core Applications

Depending on the type of application and the target environment .Net core offers different types of packaging and deployment. Mainly there are 2 types of deployment framework-dependent deployment and self-contained deployment.

Sunday, January 6, 2019

.NET Core command-line interface (CLI) tools

The .Net Core CLI (Command Line Interface) tools are a set of command line tools, which come along with the .Net core installation. The CLI tools can be used preform operations like create, build, publish and other operations on .Net core applications.

By default, the CLI installs in a side-by-side (SxS) manner, so multiple versions of the CLI tools can coexist on a single machine. The CLI command structure consists of the driver dotnet, the command, and possibly command arguments and options.

Friday, January 4, 2019

Hello World console App using .Net Core

In the previous post Getting started with .Net Core, we saw on how to setup the environment to create .Net Core applications, once the environment is setup we can go ahead and create .Net Core applications.

In the post we shall create a simple Hello World console application in .Net Core
First create a folder HelloConsole, our sample files will be created inside this folder. Open a command prompt and navigate to this folder. Once in the folder run the following command in the command prompt.

Getting started with .Net Core

.Net Core is an open-source development platform developed and maintained by Microsoft. The main idea behind creation of .Net Core is cross platform compatibility. Let us see how to setup the environment and get started with .Net Core in Windows platform.

The first thing to get started with .Net Core application development is to download the .Net Core SDK from Microsoft website.

https://dotnet.microsoft.com/download

Two flavors of .Net core downloads are available in Microsoft’s website.