ASP.NET Core is a Cross-platform, High-performance, Open-source framework for building modern, cloud-enabled, Internet-connected apps. With ASP.NET Core, you can:
- Build web apps and services, Internet of Things (IoT) apps, and mobile backends.
- Use your favorite development tools on Windows, macOS, and Linux.
- Deploy to the cloud or on-premises.
What are some of the new features introduced in the latest version of .NET Core?
The latest version of .NET Core, as of my knowledge cutoff date of September 2021, is .NET 6.0. Some of the new features introduced in this version include:
Performance improvements: .NET 6.0 includes several performance improvements, including faster startup times and reduced memory usage for ASP.NET Core applications.
Single-file applications: .NET 6.0 includes support for building single-file applications, which can simplify deployment and distribution of .NET Core applications.
Hot reload: .NET 6.0 includes support for hot reload, which allows developers to make changes to code while an application is running and see the changes immediately without restarting the application.
HTTP3 support: .NET 6.0 includes support for HTTP3, the latest version of the HTTP protocol, which can improve performance and security for web applications.
- You have cross-platform needs: If your application (web/service) needs to run on multiple platforms (Windows, Linux, and macOS), use .NET Core.
- You're targeting microservices.
- You're using Docker containers.
- You need high-performance and scalable systems.
- You need side-by-side .NET versions per application.
What are the new features provided by dot net core?
Below are new features provided by dot net core framework
- It is an open-source. So the community can contribute.
- It is lightweight and gives high performance.
- Dot net core introduced a new webserver called “Kestrel” which can work on cross-platform, it means your web application can run on other platforms like Linux, Mac, etc.
- It supports an in-built dependency injection, you do not need to install any third party DLL for it.
- Now dot net core unified the MVC Controller and API Controller.
- Side-by-side app versioning, It means If I have 2 applications A and B, A can target .NET Core 2.1 and B can target .NET Core 2.2.
- Razor pages more code-focused
- You can host your application on IIS, Nginx, Docker, Apache, and self-Host.
- Configure your appsettings.json based on the hosting environment.
- Great support for the cloud.
What is a Host and what’s the importance of Host in ASP.NET Core application?
ASP.NET Core apps require a host in which it is execute. The host is responsible for application startup and lifetime management. Other responsibility of host’s includes ensuring the application’s services and the server are available and properly configured. Don’t confuse yourself with a Server. The host is responsible for starting the app and its management, where the server is responsible for accepting HTTP requests. The host is configured to use a particular server; the server is unaware of its host.
What is the role of IHostingEnvironment interface in ASP.NET Core?
ASP.NET Core offers an interface named IHostingEnvironment, allows you to programmatically retrieve the current environment so you can have an environment-specific behaviour. By default, ASP.NET Core has 3 environments Development, Staging, and Production.
What is Kestrel?
Kestrel is a fast, new cross-platform web server introduced in dot net core that can run your web application on Linux, macOS, etc.
What is Middleware in ASP.NET Core
A Middleware is nothing but a component (class) which is executed on every request in ASP.NET Core application. In the classic ASP.NET, HttpHandlers and HttpModules were part of request pipeline. Middleware is similar to HttpHandlers and HttpModules where both needs to be configured and executed in each request. Each middleware adds or modifies http request and optionally passes control to the next middleware component.
By convention, a middleware component is added to the pipeline by invoking a Use... extension method in the Startup.Configure method. For example, to enable rendering of static files, call UseStaticFiles.
ASP.NET Core includes a rich set of built-in middleware. Custom middleware components can also be written.
Static Files
By default, an asp.net core application will not serve static files. The default directory for static files is wwwroot and this directory must be in the root project folder
By default, UseStaticFiles() middleware only serves the static files that are in wwwroot folder. We can also serve static files outside of the wwwroot folder if you want to.
Serving a default document
Please Note : UseDefaultFiles must be called before UseStaticFiles to serve the default file. UseDefaultFiles is a URL rewriter that doesn't actually serve the file. It simply rewrites the URL to the default document which will then be served by the Static Files Middleware. The URL displayed in the address bar still reflects the root URL and not the rewritten URL.
If you want to use another document like foo.html for example as your default document, you can do so using the following code.
Program.cs : ASP.NET Core Program class file is place where we can create a host for the web application.
UseFileServer Middleware
UseFileServer combines the functionality of UseStaticFiles, UseDefaultFiles and UseDirectoryBrowser middleware. DirectoryBrowser middleware, enables directory browsing and allows users to see files within a specified directory. We could replace UseStaticFiles and UseDefaultFiles middlewares with UseFileServer Middleware. Reference: Click here
UseDeveloperExceptionPage Middleware
UseDeveloperExceptionPage Middleware must be plugged into the request processing pipeline as early as possible, so it can handle the exception and display the Developer Exception Page if the subsequent middleware components in the pipeline raises an exception.
Configuring ASPNETCORE_ENVIRONMENT variable
We use this variable to set the environment for our application. On our local development machine we usually set this environment variable in launchsettings.json file. We can also set it in the operating system if we want to.
Accessing ASPNETCORE_ENVIRONMENT variable value
Out of the box, ASP.NET core provides IHostingEnvironment service which we can use to access ASPNETCORE_ENVIRONMENT variable value.
If you have the environment variable set in both the places i.e launchsettings.json file and in the operating system, then the values in launchsettings.json file overrides the value specified at the operating system level.
Useful methods of IHostingEnvironment service
Use the following methods of IHostingEnvironment service to identify the environment in which our application is running.
- IsDevelopment()
- IsStaging()
- IsProduction()
What if you have a custom environment like UAT (User Acceptance Testing) or QA (Quality Assurance) environment. Well, custom environments like these are also supported in ASP.NET core. For example, to check if the environment is UAT, use IsEnvironment() method as shown below.
Setup mvc in asp.net core
Two steps to setup MVC in ASP.NET Core Application
Step 1 : In ConfigureServices() method of the Startup class in Startup.cs file, include the following line. This line of code adds the required MVC services to the dependency injection container in asp.net core.
Step 2 : In the Configure() method, add UseMvcWithDefaultRoute() midddleware to our application's request processing pipeline. Modify the code as shown below.
Notice, we placed UseStaticFiles() middleware before UseMvcWithDefaultRoute() middleware. This order is important, because if the request is for a static file like an image, css or JavaScript file, then UseStaticFiles() middleware will handle the request and short-circuit the rest of the pipeline.
So if the request is for a static file, UseMvcWithDefaultRoute() middleware is not executed, there by avoiding the unnecessary processing.
On the other hand, if the request is an MVC request, UseStaticFiles() middleware will pass that request to UseMvcWithDefaultRoute() middleware which will handle the request and produces the response.
AddMvc() v/s AddMvcCore()
As the name implies, AddMvcCore() method only adds the core MVC services. On the other hand, AddMvc() method adds all the required MVC services. AddMvc() method calls AddMvcCore() method internally, to add all the core MVC services. So if we are calling AddMvc() method there is no need to explicitly call AddMvcCore() method again.
ASP.NET Core dependency injection
Registering Services with the ASP.NET Core Dependency Injection Container :
ASP.NET core provides the following 3 methods to register services with the dependency injection container. The method that we use determines the lifetime of the registered service. Click here
- AddSingleton() - As the name implies, AddSingleton() method creates a Singleton service. A Singleton service is created when it is first requested. This same instance is then used by all the subsequent requests. So in general, a Singleton service is created only one time per application and that single instance is used throughout the application life time.
- AddTransient() - This method creates a Transient service. A new instance of a Transient service is created each time it is requested.
- AddScoped() - This method creates a Scoped service. A new instance of a Scoped service is created once per request within the scope. For example, in a web application it creates 1 instance per each http request but uses the same instance in the other calls within that same web request.
HomeControllor.cs class
_ViewImports.cshtml in ASP.NET Core MVC
_ViewImports.cshtml file is usually placed in the Views folder. It is used to include the common namespaces so we do not have to include them in every view that needs those namespaces. Click here for more.
UseMvc or UseMvcWithDefaultRoute
If you want to define your own route templates and want to have more control over the routes, use UseMvc() method, instead of UseMvcWithDefaultRoute() method.
Attribute Routing in ASP.NET Core MVC: click here
Tools to install client-side packages
There are many tools that we can use with Visual Studio to install client-side packages like Bootstrap and jQuery. For example we could use tools like Bower, NPM, WebPack etc.
However, we are not going to use any of these tools. We will instead use Library Manager (LibMan for short). Library Manager is a light-weight, client-side library acquisition tool. It downloads client-side libraries and frameworks from the file system or from a CDN (Content Delivery Network).
libman.json file: libman.json is the Library Manager manifest file. This file contains the entry for the library that installed. We can directly edit the manifest file to install client-side packages, instead of using the user interface provided by LibMan. Click here
What are Tag Helpers
Tag Helpers are server side components. They are processed on the server to create and render HTML elements in Razor files.
generates
What is EF Core
EF Core is an ORM (Object-Relational Mapper).
EF core is lightweight, extensible, and open source software. Like .NET Core, EF Core is also cross platform. It works on windows, Mac OS, and Linux. EF core is Microsoft’s official data access platform.
What is ORM
ORM stands for Object-Relational Mapper and it enables developers to work with a database using business objects. As a developer we work with the application business objects and the ORM generates the SQL that the underlying database understands. In-short, an ORM, eliminates the need for most of the data-access code that developers usually need to write.
EF Core Database First Approach
Sometimes we may have an existing database. When we have a database and the database tables already, we use the database first approach. With the database first approach, EF Core creates the DBContext and Domain classes based on the existing database schema.
EF Core Database Providers
EF Core supports many relational and even non relational databases. EF Core is able to do this by using plug-in libraries called the database providers. These database providers are available as NuGet packages.
List of EF Core Database Providers
https://docs.microsoft.com/en-us/ef/core/providers/
A database provider, usually sits between EF Core and the database it supports. The database provider contains the functionality specific to the database it supports. Functionality that is common to all the databases is in the EF Core component. Functionality that is specific to a database, for example, Microsoft SQL Server specific functionality is with-in the SQL Server provider for EF Core.
To install Entity Framework Core and to be able to use SQL server as the database for your application, you need to install the following nuget packages.
Microsoft.EntityFrameworkCore.SqlServer - This nuget package contains SQL Server specific functionality
Microsoft.EntityFrameworkCore.Relational - This nuget package contains functionality that is common to all relational databases
Microsoft.EntityFrameworkCore - This nuget package contains common entity frameowrk core functionality
When we install Microsoft.EntityFrameworkCore.SqlServer package, it also installs all the other dependant nuget packages automatically.
DbContext in entity framework core
One of the very important classes in Entity Framework Core is the DbContext class. This is the class that we use in our application code to interact with the underlying database. It is this class that manages the database connection and is used to retrieve and save data in the database.
For the DbContext class to be able to do any useful work, it needs an instance of the DbContextOptions class.
The DbContextOptions instance carries configuration information such as the connection string, database provider to use etc.
To pass the DbContextOptions instance we use the constructor as shown in the example below.
The DbContext class includes a DbSet[TEntity] property for each entity in the model.
Using sql server with entity framework core
When using Entity Framework Core, one of the important things that we need to configure is the database provider that we plan to use. Click here
We want to configure and use Microsoft SQL Server with entity framework core. We usually specify this configuration in ConfigureServices() method in Startup.cs file.
UseSqlServer() extension method is used to configure our application specific DbContext class to use Microsoft SQL Server as the database.
To connect to a database, we need the database connection string which is provided as a parameter to UseSqlServer() extension method
Instead of hard-coding the connection string in application code, we store it appsettings.json configuration file.
To read connection string from appsettings.json file we use IConfiguration service GetConnectionString() method.
Entity framework core migrations- Click here, Click here
Migration is an entity framework core feature that keeps the database schema and our application model classes (also called entity class) in sync.
If you have not executed at-least the initial migration in your application you might get the following SqlException
SqlException: Cannot open database "EmployeeDB" requested by the login.
This is because we do not have the database created yet. One way to create the database is by
- Creating a migration first and then
- Executing that migration
We will be using the following commands to work with migrations in entity framework core.
Add-Migration: Adds a new migration
Update-Database: Updates the database to a specified migration
Remove-Migration: It only removes one migration at a time and that too only the latest migration that is not yet applied to the database. If all the migrations are already applied, executing Remove-Migration command throws the following exception.
Creating a Migration in Entity Framework Core
The following command creates the initial migration. InitialCreate is the name of the migration.
When the above command completes, you will see a file in the "Migrations" folder that contains the name InitialCreate.cs. This file has the code required to create the respective database tables.
Update-Database in Entity Framework Core
We need to execute the migration code to create the tables. If the database does not exist already, it creates the database and then the database tables. For updating the database, we use Update-Database command. To the Update-Database command we may pass the migration name we want to execute. If no migration is specified, the command by default executes the last migration.
Entity framework core seed data Click here
If you are using Entity Framework Core 2.1 or later there is a new method of seeding database data. In your application DbContext class, override OnModelCreating() method.
HasData() method configures entity to have the specified seed data.
File upload in asp.net core mvc: Click here
Centralised 404 error handling in ASP NET Core Click here
Along the way, we will discuss the following 3 middleware components that deal with status code pages in asp.net core
- UseStatusCodePages
- UseStatusCodePagesWithRedirects
- UseStatusCodePagesWithReExecute
Types of 404 errors
In ASP.NET Core there are 2 types of 404 errors that could happen
- Type 1 : Resource with the specified ID does not exit.
- Type 2 : The provided URL does not match any route in our application.
The following is code in Configure() method of Startup class in Startup.cs file. As you might already know, this Configure() method configures the HTTP request processing pipeline for our asp.net core application.
UseStatusCodePages Middleware
This is the least useful of the 3 status code middleware components. For this reason, we rarely use it in a real world production application. To use it in an application and see what it can do, plug it into the http processing pipeline as shown below.
With UseStatusCodePages Middleware configured, if we navigate to a url which does not exist, it returns simple text response.
UseStatusCodePagesWithRedirects Middleware
In a production quality application we want to intercept these non-success http status codes and return a custom error view. To achieve this, we can either use UseStatusCodePagesWithRedirects middleware or UseStatusCodePagesWithReExecute middleware.
With the following line in place, if there is a 404 error, the user is redirected to /Error/404. The placeholder {0}, in "/Error/{0}" will automatically receive the http status code.
Difference between UseStatusCodePagesWithRedirects and UseStatusCodePagesWithReExecute
- UseStatusCodePagesWithRedirects : Send 302 to Client. It redirects you to error controller action method.
- UseStatusCodePagesWithReExecute : Send Original Status Code and Executes handler for redirect URL. UseStatusCodePagesWithReExecute is just rendering page with out redirecting.
- Click here for more in detail
Global exception handling in asp net core mvc Click here
Step 1 : For a non-development environment, add the Exception Handling Middleware to the request processing pipeline using UseExceptionHandler() method. We do this in the Configure() method of the Startup class. Exception Handling Middleware looks for ErrorController.
Step 2 : Implement the ErrorController that retrieves the exception details and returns the custom Error view.
Step 3 : Implement Error View
Logging exceptions in ASP NET Core
Inject an instance of ILogger where you need the logging functionality
- LogError() method logs the exception under Error category.
- LogWarning() method logs the message under Warning category.
ASP.NET Core Identity
ASP.NET Core Identity is a membership system. It allows us to create, read, update and delete user accounts. Supports account confirmation, authentication, authorization, password recovery, two-factor authentication with SMS. It also supports external login providers like Microsoft, Facebook, Google etc. We will discuss implementing these features in our upcoming videos in this series. Click here
The following are the steps to add and configure ASP.NET Core Identity
Step 1 : Inherit from IdentityDbContext class
Step 2 : Add ASP.NET Core Identity Services
Step 3 : Add Authentication middleware to the request pipeline
Step 4 : Add Identity Migration: This migration contains code that creates the tables required by the ASP.NET Core Identity system.
Step 5 : Generate ASP.NET Core Identity Tables
ASP NET Core Identity UserManager and SignInManager Click here
Create a new user, using UserManager service provided by asp.net core identity:
UserManager<IdentityUser> class contains the required methods to manage users in the underlying data store. For example, this class has methods like CreateAsync, DeleteAsync, UpdateAsync to create, delete and update users.
Sign-in a user using SignInManager service provided by asp.net core identity:
SignInManager<IdentityUser> class contains the required methods for users signin. For example, this class has methods like SignInAsync, SignOutAsync to signin and signout a user.
Both UserManager and SignInManager services can be injected into the AccountController using constructor injection
ASP NET core remote validation
Remote validation allows a controller action method to be called using client side script. This is very useful when you want to call a server side method without a full page post back.
ASP.NET Core MVC uses jQuery remote() method which in turn issues an AJAX call to invoke the server side method. Click here
Extend IdentityUser in ASP NET Core Click here
You can name the class that extends the IdentityUser class anything you want.In the example below, ApplicationUser class extends the IdentityUser class. We have included just one custom property City, but you can include as many properties as you want.
Creating roles in asp net core
To create a user in asp.net core we use UserManager class. Similarly, to create a role, we use RoleManager class provided by asp.net core.
The built-in IdentityRole class represnts a Role.
RoleManager class performs all the CRUD operations i.e Creating, Reading, Updating and Deleting roles from the underlying database table AspNetRoles Click here
0 comments:
Post a Comment