Dot Net Core

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

ASP.

NET CORE
ASP.NET CORE MVC
ASP.NET CORE IDENTITY --For Authentication
ENTITY FRAMEWORK ---For Data Access

ASP.NET CORE:
- Cross Platform, High Performance, Open Source framework to build Cloud based, Internet connected apps.

- Redesign of ASP.Net 4.X. Was initially called .NET 5, Later called as .NET CORE.
- One programming model for .NET CORE MVC & WEB API. -------------xxx
- Built In Support for Dependency Injection. ------------------------xxx

Basis .NET Core .NET Framework


When we talk about .NET Core it is defined as the .Net Framework is a full-fledged development framework. The
Platform or platform on which frameworks like ASP.NET Core and the framework provides all the basic requirements for the
Framework Universal Windows Platform rely and extend the .NET development of applications such as UI, DB connectivity,
Core platform’s functionalities. services, APIs, etc.
The.Net Framework includes certain open source
Open-Source .NET Core is an open-source platform.
components.
It is based on the concept of “create once, run
anywhere.” Because it is cross-platform, it is compatible
.NET Framework is compatible with Windows OS(operating
with a variety of operating systems, including Windows,
Cross- system) only
Linux, and Mac OS.
Platform
Can be hosted on IIS only.
Can be hosted on IIS, Docker--xxx,Apache--xxx, Self Host
in your own process.
Application The Application Model of .Net Core includes ASP.NET and The Application Model of the .NET Framework includes
models windows universal apps. WinForms, ASP.NET, and WPF.
Installation .Net Core is the cross-platform, hence it needs to be .NET Framework has a single packaged installation and
installed independently. runtime environment for windows.
.NET Core has support for microservices. , NET Core When we talk about the .NET Framework it does not allow for
Microservices
allows a mix of technologies that can be minimalized for the construction and deployment of microservices in multiple
support
each microservice. languages.
.NET Core has no support for WCF( Windows When it comes to WCF (Windows Communication
REST services
Communication Foundation ) services. You would always Foundation) services, the.NET Framework is a fantastic choice.
support
need to create a REST API. It also works with RESTful services.
Performance  .NET core provides high scalability and performance in
.NET Framework is less scalable and provides low
and comparison to .NET Framework because of its
performance in comparison to .NET Core.
Scalability architecture.
Feature such as Code Access Security is not present
Security in .NET core so .NET Framework does have the edge in .NET Framework has this feature called code access security.
that case.
Focus on .NET Core focuses to develop apps in a variety of domains
.NET Framework is limited to window OS.
devices like gaming, mobile, IoT, AI, etc.
Mobile.NET Core is compatible with various operating On the other .NET Framework is only compatible with
Compatibility
systems-Windows, Linux, and Mac OS. Windows OS.
Mobile apps are becoming more important for
Mobile businesses. .NET Core has some support for mobile apps. On the other hand, the .NET Framework does not support
Development It’s compatible with Xamarin and other open-source their development at all, and that is a problem.
platforms for mobile applications.
For all platforms,.NET Core provides a very lightweight
.NET Framework is too heavy for CLI. some developers prefer
CLI Tools CLI( Command Line Interface). There’s always the option
working on CLI rather than on IDE.
of switching to an IDE.
When a new version of.NET Core is installed, it is updated
on one computer at a time, resulting in new IDE In the case of .NET Framework, when the updated version
Deployment
directories/folders being created in the existing program is released it is first deployed on the internet information
Model
without affecting it. As a result,.NET Core provides a solid service only.
and adaptable deployment model.
Packaging All the libraries of the .NET Framework are packed and
.NET Core is shipped as a collection of Nuggets packages.
and shipping shipped together.
NET Core Vs .NET Framework – Which is Better?

The answer to this question depends on the project requirement, what our project demands for so here are some points that we have to consider to choose best for our
project out of the .NET Framework and .NET Core.

Prefer or choose .NET Core if 

1. The project demands cross-platform integration.


2. The project requires the development of microservices.
3. Project relies heavily on CLI( Command Line Interface) as .NET Core is suitable for CLI.

Prefer or choose .NET Framework if 

1. Applications are already running on .NET Framework.


2. The Applications require technologies like workflow, webforms, or WCF that are not present in .NET Core.
3. Applications are built to run on Windows alone.

.NET Core Composition


The .NET Core Framework composed of the following parts:
 CLI Tools: A set of tooling for development and deployment.
 Roslyn: Language compiler for C# and Visual Basic
 CoreFX: Set of framework libraries.
 CoreCLR: A JIT based CLR (Command Language Runtime).

.NET Core Version History


Version Latest Version Visual Studio Release Date End of Support
.NET 5 Preview 1 VS 2019 16th March, 2020
.NET Core 3.x - latest 3.1.3 VS 209 24th March, 2020 12th March, 2022
Version Latest Version Visual Studio Release Date End of Support
.NET Core 2.x 2.1.17 VS 2017, 2019 24th March, 2020 21st August, 2021
.NET Core 1.x 1.1.13 VS 2017 14th May, 2019 27th May, 2019

Both, .NET 3.1, and .NET Core 2.1 will have long term support.

.NET Core 3.x applications only run on .NET Core Framework.

.NET Core 2.x applications run on .NET Core as well as .NET Framework.
Build ASP.NET CORE:
EMPTY- Bare min.content to display Hello World. Setup from scratch manually.

API - TO create ASP.NET CORE Restful Http service. It doesn’t have a UI so it doesnt create UI Folders such as Views, css, js etc. It only has Controllers Folder.

Web Application - Uses New razor pages framework. Slimmer version of MVC

Web Application (Model - View - Controller) -


wwwroot folder (CSS Files, JS Files and library files required for web application )
Model folder(ErrorVIewModel.cs),
views folder(Home(Index.cshtml, Privacy.cshtml), Shared(_Cookie, _layout.cshtml, )),
controllers(home controller)

Razor Class Library - to create a reusable razor class lib project. Contains all reusable UI pieces like data models, page models. Can be re used in multiple apps
Angular - .net with angular
React.js -
React .js and Redux -

.csproj:

Note:
ASP.NET Core project files and folders are synchronized with physical files and folders. If you add a new file or folder in project folder then it will directly reflect in
the solution explorer. You don't need to add it in the project explicitly by right clicking on the project.
Main calls CreateWebHostBuider method
CreateWebHostBuider calls CreateDefaultBuilder(args) static method of WebHost Class.
CreateDefaultBuilder method sets up the web host that hosts our appl with preconfigured defaults.& configures logging.

ASP.NET core app can be hosted on: (a) InProcess (b)OutOfProcess


In .csproj file <AspNetCoreHostingModel></AspNetCoreHostingModel>
(A) InProcess
In .csproj file <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
One Web server - IIS
Calls UseIIS() to host app inside IIS Worker process
Worker process incase of IIS : w3wp.exe and incase of IISExpress is iisexpress.exe
Delivers significantly higher req throughput that OutOfProcess hosting.

To get the process name executing app:


System.Diagnostics.Process.GetCurrentProcess().ProcessName in Startup.cs In place of printing “HelloWorld”
By default visual studio uses IISExpress- light weight of IIS

(B) OutOfProcess
In .csproj file <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
OR completely remove <AspNetCoreHostingModel></AspNetCoreHostingModel> from .csproj, By default it’s OutOfProcess hosting.

Uses 2 web servers- Internal & External


Internal web server - Kestral
External Web server- IIS, Nginx, Apache depending on OS
Kestral:
 Cross platform web server, included by default in asp.net core
 Can be used by itself as edge server
 Process used to host app is dotnet.exe
 Inprocess or OutOfProcess, when .net core app is run from CLI, it uses Kestral. The process executing would be dotnet.exe

Depending on app, it can vary whether we need an External server.


Case 1:
when only 1 server is used (running from CLI ==>> command is dotnet run)
Kestral can b used as Internet facing web server
Case 2:
Kestral can b used in combo. With reverse proxy

Launchsettings.json in Properties folder:


The settings are used when we run asp.net proj from cli or VS. Not needed to publishing. If these settings are req. To be published then copy them to appsettings.json
2 profiles--1st profile is for IIS when app is run from VS, 2 nd profile has name of project & it is for app when it is run from CLI
Application url has port number
Configure ssl port
Chnge environment variable => effetcts startup.cs code (if (env.dev)===code part
YOu can directly change the values from launchsettings.json ss shown above or it ca also be done from UI. Right click on solution - Properties -Debug. As shown below
Configurations sources in asp.net core:
1. Files(appsettings.json, appsettings.(Environment).json)
2. User secrets
3. Environment variables- above ss -launchsettings
4. Cmd line arguments
To access configuration info:
IConfiguration Service - setup in such a way that it gets config info from all above sources in the order specified above. The default order is set by
CreateDefaultBuilder(args) static method of WebHost Class.
If same settings are present in more than one config then the latest setting will be overriden. Ex. Cmd line overrides Env variables.
(Command: dotnet run KeyName=”Value”)

appsettings.json:
Usually stored as Key value pairs
Example:
Added MyKey in appsettings.json

Inject Iconfiguartion in startup.cs -> Using Microsoft.Extensions.Configurations and then ctor+ tab (twice) for constructor, print from startup.cs
Appsettings.{Environment}.json:
Appsettings.Development.json
Appsettings.Staging.json
Appsettings.Production.json
** Settings in Appsettings.{Environment}.json will override settings in Appsettings..json

Middleware:
Its a very broad term.
A piece of software that can handle HTTP Request or HTTP Response.
Middleware components that we use to setup a request pipeline. It is this pipeline that determines how a request is processed. The request pipelone is configured as part
of application startup by Configure() Method in Startup Class.
As we know that prog execution starts from Main() which calls CreateWebHostBUilder() which calls CreateDefaultBuilder() method which sets up default WebHost.
As part of setting up the web host, it also sets up the Starup by .UseStartup<Startup> Extension method.
Has access to both incoming req and outgoing response.

Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component:

 Chooses whether to pass the request to the next component in the pipeline.
 Can perform work before and after the next component in the pipeline.

Request delegates are configured using Run, Map, and Use extension methods.

 Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-
circuiting the pipeline. When a middleware short-circuits, it's called a terminal middleware because it prevents further middleware
from processing the request.
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0

*****https://www.tutorialsteacher.com/core/aspnet-core-middleware
We can configure middleware in the Configure method of the Startup class
using IApplicationBuilder instance. The following example adds a single middleware using Run method
which returns a string "Hello World!" on each request.

public class Startup


{
public Startup()
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//configure middleware using IApplicationBuilder here..
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");

});

// other code removed for clarity..


}
}

In the above example, Run() is an extension method on IApplicationBuilder instance which adds a terminal


middleware to the application's request pipeline. The above configured middleware returns a response with
a string "Hello World!" for each request.

Method Signature:
public static void Run(this IApplicationBuilder app, RequestDelegate handler)
Method Signature:
public delegate Task RequestDelegate(HttpContext context);

Configure Multiple Middleware


Mostly there will be multiple middleware components in ASP.NET Core application which will be executed
sequentially. The Run method adds a terminal middleware so it cannot call next middleware as it would be
the last middleware in a sequence. The following will always execute the first Run method and will never
reach the second Run method.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World From 1st Middleware");
});

// the following will never be executed


app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World From 2nd Middleware");
});
}

To configure multiple middleware, use Use() extension method. It is similar to Run() method except that it


includes next parameter to invoke next middleware in the sequence. Consider the following example.

Example: Use()
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Hello World From 1st Middleware!");

await next();
});

app.Run(async (context) =>


{
await context.Response.WriteAsync("Hello World From 2nd Middleware");
});
}

The above example will display Hello World From 1st Middleware!Hello World From 2nd Middleware!  in the
browser.

Thus, we can use Use() method to configure multiple middlewares in the order we like.

Add Built-in Middleware Via NuGet


ASP.NET Core is a modular framework. We can add server side features we need in our application by
installing different plug-ins via NuGet. There are many middleware plug-ins available which can be used in
our application.

The followings are some built-in middleware:

Middleware Description
Authentication Adds authentication support.
CORS Configures Cross-Origin Resource Sharing.
Routing Adds routing capabilities for MVC or web form
Session Adds support for user session.
StaticFiles Adds support for serving static files and directory browsing.
Diagnostics Adds support for reporting and handling exceptions and errors.

Let's see how to use Diagnostics middleware.


Diagnostics Middleware
Let's install and use Diagnostics middleware. Diagnostics middleware is used for reporting and handling
exceptions and errors in ASP.NET Core, and diagnosing Entity Framework Core migrations errors.

Open project.json and add Microsoft.AspNetCore.Diagnostics dependency if it is not added. Wait for some
time till Visual Studio restores the packages.

This package includes following middleware and extension methods for it.

Middleware Extension Method Description


DeveloperExceptionPageMiddlewar UseDeveloperExceptionPage() Captures synchronous and asynchronous
e exceptions from the pipeline and generates
HTML error responses.
ExceptionHandlerMiddleware UseExceptionHandler() Catch exceptions, log them and re-execute
in an alternate pipeline.
StatusCodePagesMiddleware UseStatusCodePages() Check for responses with status codes
between 400 and 599.
WelcomePageMiddleware UseWelcomePage() Display Welcome page for the root path.

We can call respective Use* extension methods to use the above middleware in the configure method of
Startup class.

Let's add welcomePage middleware which will display welcome page for the root path.

Example: Add Diagnostics Middleware


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseWelcomePage();
//other code removed for clarity
}

The above example will display the following welcome page for each request.

This way we can use different Use* extension methods to include different middleware.

Configure:
Method that sets up a request processing pipeline for ASP.NET CORE application.
By deafult contains 2 Middleware. => UseDeveloperExceptionPage(), Run(async (context) )

Static FIles in ASP.NET CORE:


2 requirements:
1. They must be present in wwwroot folder
2. To be able to access a static file call a middleware: app.UseStaticFiles(); in Configure method.

By default, a default page can have a name from one of the foll:
Default.htm
Default.html
Index.htm
Index.html

TO access default document use middleware: UseDefaultFiles();

UseDefaultFiles shd be mentioned b4 UseStaticFiles for it to work.

=>To change default doc


DefaultFilesOptions def= new DefaultFilesOptions ()
def.DefaultFileNames.Clear();
def.DefaultFileNames.Add(“abc.html”);
app.UseDefaultFiles(def);

UseFIleServer combines functionality of UseStaticFiles , UseDefaultFiles and UseDirectoryBrowser middleware.


Above code can also be written with UseFIleServer as:

DeveloperException Page:
The Developer Exception Page displays detailed information about unhandled request exceptions. ASP.NET Core apps enable the
developer exception page by default when running in the Development environment.

The developer exception page runs early in the middleware pipeline, so that it can catch unhandled exceptions thrown in
middleware that follows.

If the Exception Page is run later in the middleware pipeline, it cannot display the exception page.

Detailed exception information shouldn't be displayed publicly when the app runs in the Production environment.

The Developer Exception Page can include the following information about the exception and the request:

 Stack trace
 Query string parameters, if any
 Cookies, if any
 Headers
Configuring Using Environment Variables:
ASPNETCORE_ENVIRONMENT Variable sets the runtime env.
Use IHostingEnvironment service to access the runtime env.
Can be set from:
-Launchsettings.json
-Control Panel
-Right click- properties - Debug- set

If env variable is present in both launchsettingd & control panel, then the value value from control panel will be overridden to the
value from launchsettings.json

TO print env variable:: kudvenkat video

By Default, we have IsDevelopemnt(), IsStaging(), IsProduction()


For a custom env: if( env.IsEnvironment(“UAT”)), If env variable iin launchsettings is UAT, it works.
MVC:
Architectural design pattern for implementing User Interface Layer

Model: Set of classes that repr data and the logic to manage the data
Employee class has data which we want to display, EmpRepository class knows how to Save and manage the data from db
Here, we have used interface IEmployeeRepository to make use of Dependency Injection so that we can create loosely coupled/
easily testable systems.
Setup MVC
Step 1: add req mvc services to the built in dependency injection container
//services.AddMvc() into the ConfigureServices() method in Starup class
Step 2: Add MVC middleware
Add Mvc middleware in Configure()
//app.UseMvcWithDefaultRoute() or app.UseMvc()
AddMvc() vs AddMvcCore():
Controller:
Views:

By default, when executed the control goes to the View depending on the name of Action method.
If the action method is: public ViewResult Details() in Home Controller., then it looks for ‘Details.cshmtl’ View in ‘Home’ folder in ‘Views’ (Views/Home/Details) By Default
TO change the default view: mention the name of view to be returned while returning as shown below
If the req view is in another folder, mention the exact path:

Extension .cshtml is not required while using a relative path but req. while mentioning the absolute path as above

You might also like