0% found this document useful (0 votes)
216 views

Core (1 2 3)

ASP.NET Core is a free, open-source, and cross-platform framework for building web applications and services. It is a complete rewrite of ASP.NET, making it modular and cross-platform. ASP.NET Core can run on Windows, Linux and macOS. It uses a new lightweight and modular .NET Core runtime and is designed for cloud-optimized development. Some key features include being open-source, cross-platform, modular, cloud-optimized and using a unified MVC and Web API framework. It also has improvements in performance, maintainability and testing compared to earlier versions of ASP.NET.

Uploaded by

Naazir jema
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
216 views

Core (1 2 3)

ASP.NET Core is a free, open-source, and cross-platform framework for building web applications and services. It is a complete rewrite of ASP.NET, making it modular and cross-platform. ASP.NET Core can run on Windows, Linux and macOS. It uses a new lightweight and modular .NET Core runtime and is designed for cloud-optimized development. Some key features include being open-source, cross-platform, modular, cloud-optimized and using a unified MVC and Web API framework. It also has improvements in performance, maintainability and testing compared to earlier versions of ASP.NET.

Uploaded by

Naazir jema
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

ASP.

NET Core
2023
Abdullah Hoolif
What is Asp.Net Core?
ASP.NET Core is a free, open-source, and cloud-optimized framework that can run on Windows, Linux,
or macOS. You can say it is the new version of ASP.NET. The framework is a complete rewrite from
scratch in order to make it open-source, modular, and cross-platform.

ASP.NET Core:

-> Web Framework

-> Open-Source

-> Cross-Platform

-> Modular

-> Cloud Optimize

-> Runs on top of the .NET Core and .NET Framework


What is .NET Core?

Core framework can be used to build different types of applications such as

console

desktop

web

mobile

cloud, etc…
History of ASP.NET

As we know, ASP.NET is the framework that has been used to develop data-driven web applications
for many years. Since then, the ASP.NET Framework went through a steady evolutionary change, and
finally, the most decent evolution is ASP.NET Core.

The ASP.NET Core is not a continuous part of the ASP.NET 4.x Framework. Instead, it is a completely
new framework.

This Framework is an actual re-write of the current ASP.NET 4.x Framework, but with much smaller
and a lot more modular.

Some people think that many things remain the same, but that is not completely true. The ASP.NET
Core is actually a big fundamental change to the ASP.NET Framework.
.NET Core Characteristics:
Open-source Framework: .NET Core is framework maintained by Microsoft and available on
GitHub under MIT and Apache 2 Licenses. You can view, download, or contribute to the source
code using the following GitHub repositories:

.NET Core Runtime: https://github.com/dotnet/runtime

.NET Core SDK: https://github.com/dotnet/sdk

ASP.NET Core: https://github.com/dotnet/aspnetcore

Language Compiler Platform Roslyn: https://github.com/dotnet/roslyn


.NET Core Characteristics:
Cross-Platform: .NET Core runs on Windows, Linux, and macOS operating systems. There is different runtime
for each operating system that executes the code and generates the same output.

Consistent across Architecture: Execute the code with the same behavior in different instruction set
architectures, including x64, x86, and ARM.

Wide range of Applications: Various types of applications can be developed and run on .NET Core platforms
such as Console, Desktop, Web, Mobile, Cloud, IoT, ML, Microservices, Gaming, etc…

Support Multiple Languages: You can use C#, F#, and Visual Basic programming to develop .

Modular Architecture: .NET Core supports a modular architecture approach using NuGet Packages. There are
different NuGet Packages available for various features that can be added to the .
Conn .NET Core Characteristics:
CLI Support: Using CLI commands you can develop and run .NET applications as well as you can
also publish the application using CLI command.

Fast: ASP.NET Core no longer depends on System.Web.dll for browser-server communication.


ASP.NET Core allows us to include packages that we need for the application. This reduces the request
pipeline and improves performance and scalability.

IoC Container: One of the most important used design patterns in the real-time application is the
Dependency Injection Design Pattern. It includes the built-in IoC (Inversion of Control) container for
automatic dependency injection which makes it maintainable and testable
Unified MVC and Web API Framework:
The ASP.NET Core provides a unified programming model for developing both Web
apps and Web APIs. That means a single controller class can be used to handle both.

The Controller we create in ASP.NET Core (either Web APPs or Web APIs)

In the ASP.NET Core Web API application, the controller action method is going to
return JsonResult. At the same time if it is an ASP.NET Core Web application, then the
return type of the controller action method is going to be ViewResult.
Testing and Maintainability:
You can easily test and maintain the applications developed using the ASP.NET Core MVC framework. This is
possible because it allows you to separate different parts of your application into independent pieces and it
also allows you to test them independently. The Testing frameworks such as xUnit and MOQ can be easily
integrated into ASP.NET Core MVC application for simulating any scenario.

Integration with Modern UI Framework: It allows you to use and manage modern UI frameworks such as
AngularJS/Angular, React JS, and Bootstrap, etc
Handling Request and Response Pipeline:
We can handle the request and response in the ASP.NET Core application by using the new
Middleware Components. In earlier ASP.NET 4.x we generally use Handlers and Modules to handle
the Request and Response pipeline. The ASP.NET Core Framework provides a lot of built-in
Middleware Components and we can use those Middleware Components to handle the request and
response pipeline.

Hosting:

ASP.NET Core web application can be hosted on multiple platforms with any web server such as IIS,
Apache, etc… It is not dependent only on IIS as a standard .NET Framework.

Code Sharing: It allows you to build a class library that can be used with .NET Frameworks such as
.NET Framework 4.x or Mono. Thus, a single code base can be shared across frameworks.

Side-by-Side App Versioning: ASP.NET Core runs in .NET Core, which supports the simultaneous
running of multiple versions of applications.
Extensible Framework:
The ASP.NET Core MVC Framework is designed to be highly extensible. That means you
can create an application today, that can be extended to any levels in the future. Some of the
key features provided by this framework that give it the extensible power are as follows.

1. View Components
2. Tag Helpers
3. Routing
Language Support:
Dot Net Core Framework supports the following language i.e. using the following languages you can develop
.NET Core applications. We are going to use C# as the programming language in this course.

1. C#
2. F#
3. Visual Basic (VB)

.NET Core GitHub Repository:

.NET Core Runtime: https://github.com/dotnet/runtime


.NET Core SDK: https://github.com/dotnet/sdk
ASP.NET Core GitHub Repository: https://github.com/dotnet/aspnetcore
Download and install Visual Studio
https://visualstudio.microsoft.com/
Download and install Visual Studio
Download and install .NET Core SDK
I can verify the same using the “dotnet –version”

command as shown in the below image.

https://dotnet.microsoft.com/download
ASP.NET Core Project File
Creating ASP.NET Core Web Application

Project templates in ASP.NET Core Application


What is a Kestrel Web Server?
As we already discussed ASP.NET Core is a cross-platform framework. It means it supports
to development and run applications on different types of operating systems such as
Windows, Linux, or Mac.

The Kestrel is the cross-platform web server for the ASP.NET Core application. That means
this Server supports all the platforms and versions that the ASP.NET Core supports. By
default, it is included as the internal web server in the .NET Core application.

Before using the Kestrel server to run our application, let us first open the launchSettings.json file which is
present inside the Properties folder of your application. Once you open the launchSettings.json file you will find
the following code by default.
.NET Core Command-Line Interface
The .NET Core command-line interface (CLI) is a new cross-platform tool for creating,
restoring packages, building, running and publishing .NET applications.

We created our first ASP.NET Core application using Visual Studio in the previous chapter.
Visual Studio internally uses this CLI to restore, build and publish an application. Other higher
level IDEs, editors and tools can use CLI to support .NET Core applications.

The .NET Core CLI is installed with .NET Core SDK for selected platforms. So we don't need to
install it separately on the development machine.
How to run a .NET Core application using .NET
Core CLI?
We can also run the ASP.NET Core application from the command line using the .NET Core CLI. The CLI stands for
Command Line Interface.

When we run an ASP.NET Core application using the .NET Core CLI, then the .NET Core runtime uses Kestrel as the
webserver. We will discuss the .NET Core CLI in detail in our upcoming article. Now, let us see how to run a dot net core
application using .NET Core CLI Command.

First. open the command prompt and type “dotnet —” and press enter as shown below.

Once you change the directory to your project folder, then execute the “dotnet run” command as shown in the below
image.
Basic Commands
● new
● restore
● build
● publish
● run
● migrate
● Clean
● List
● help
● watch
Application Types:

1. NET Core with Razor Pages


2. NET Core with MVC (ASP.NET Core MVC or Core MVC or MVC Core)
3. NET Core with Web API (ASP.NET Core Web API or Core Web API or Web API
Core)
4. NET Core with Angular (Single Page Application)
5. NET Core with React JS (Single Page Application)
6. NET Core with React JS & Redux (Single Page Application)
What is MVC?

MVC stands for Model View and Controller. It is an


architectural design pattern that means this design
pattern is used at the architecture level of an
application. So, the point that you need to remember is
MVC is not a programming language, MVC is not a
Framework, it is a design pattern.
Controller: A Controller is a .cs (for C# language) file which has some methods called Action Methods.

Model :The Model is the component in the MVC Design pattern which is used to manage that data .

View: The view component in the MVC Design pattern is used to contain the logic to represent the model
data as a user interface with which the end-user can interact. Basically, the view is used to render the
domain data
xuseen

Controllers in ASP.NET MVC Application


•A controller in an ASP.NET MVC Application is a
class having a set of public methods. These public
methods of the controller class are called action
methods or simple actions. These action methods
in the ASP.NET MVC application are going to
handle the incoming HTTP Requests.
Conn.
•By convention, in ASP.NET MVC, the controller classes
should reside in the project’s root level Controllers
folder and should be inherited from the
System.Web.Mvc.Controller base class.
What is Action Method in ASP.NET Core MVC?

Actions are the methods in controller class which are responsible for returning the
view or Json data. Action will mainly have return type “ActionResult”
following categories:

1. ViewResult- Returns a ViewResult action result.


2. EmptyResult - Represents no result.
3. JsonResult - Represents a JavaScript Object Notation result that can be used
in an AJAX application.
4.
5. ContentResult - Represents a text result.
6. FileContentResult - Represents a downloadable file (with the binary content).
Miscellaneous Action Results
ActionResult

ContentResult ContentResult represents a text result.

● public ContentResult ContentResult()


● {
● return Content("I am ContentResult");
● }
ContentResult represents a text result. The default return type of a ContentResult is string, but it’s not limited
to string. We can return any type of response by specifying a MIME type, in the code.
EmptyResult

● public EmptyResult EmptyResult()



● return new EmptyResult();

EmptyResult represents an ActionResult that when executed will do nothing. We can use it when we want to
return empty result.

JsonResult
JsonResult formats the given object as JSON. JsonResult is use to return JSON-formatted data,
● public JsonResult JsonResult()
● {
● var name = "Farhan Ahmed";
● return Json(new { data=name});
● }
JsonResult formats the given object as JSON. JsonResult is use to return JSON-formatted data, it returns
JSON regardless of what format is requested through Accept header.
ViewResult

ActionResult

ActionResult is the base class of all the result type action method.

● public ActionResult About()


● {
● return View();
● }
—---------------------------------

ViewResult represents an ActionResult that renders a view to the response. It is used to render a view to
response, we use it when we want to render a simple .cshtml view.

● public ViewResult ViewResult()


● {
● return View("About","Home");
● }
Model
•The Model is the component in the MVC design pattern that manages that data i.e. state
of the application in memory. The Model contains a set of classes that represent the data
as well as logic to manage the data. So, in our example, the model is consists of Student
class to represent the student data as well as StudentBusinessLayer class to retrieve the
student data from any persistent medium like a database.

•So in short, a Model:
•In ASP.NET MVC is basically a C# class to represent the data as well as to manage the
data.
•It is accessible by both controller and view.
•It can be used to pass data from controller action methods to a view.
•It can also be used by a view to display data in a page (HTML output).
Model
Controller
View
The view is the component in MVC Design Pattern which renders the model data
as the user interface with which the end-user can interact. So, the View creates
the user interface with data from the model. In our example, we want to display
the Student information in a web page. So here the student model carried the
student data to the view. This is the student model which should be supplied by
the controller to the view. The following code does the same thing.
View
Routing in ASP.NET Core MVC
•Routing is the process through which the application matches an incoming URL
path and executes the corresponding action methods. ASP.NET Core MVC uses a
routing middleware to match the URLs of incoming requests and map them to
specific action methods.
•We can define the routes either in the Program class or as attributes. They
describe how we can match the URL paths with the action methods. We can also
use routes to generate URLs for links that are sent out in responses.
•There are two types of routing for action methods:
•Conventional Routing
•Attribute Routing
Conventional Routing
•When we create a new ASP.NET Core MVC application using the default
template, the application configures a default routing. Let’s create a new project
and examine this.
•After creating a new project with the default ASP.NET Core MVC template, let’s
have a look at the Program.cs class. We can see that the application has
configured a default routing in the Configure() method:
•app.UseRouting();
•app.MapControllerRoute(
• name: "default",
• pattern: "{controller=Home}/{action=Index}/{id?}");

What is Conventional Based Routing in
ASP.NET Core MVC Application?
In Conventional Based Routing, the route is determined based on the conventions defined in
the route templates which will map the incoming Requests (i.e. URLs) to controllers and their
action methods. In ASP.NET Core MVC application, the Convention based Routes are
defined within the Configure method of the Program.cs class file.
If the URL doesn't contain anything after the domain name, then the default controller
and action method will handle the request. For example, http://localhost:1234 would
be handled by the HomeController and the Index() method as configured in the default
parameter.
What is Attribute-Based Routing in ASP.NET
Core MVC Application?
In Attribute-Based Routing, the route is determined based on the attributes which are
configured either at the controller level or at the action method level. We can use both
Conventional Based Routing and Attribute-Based Routing in a single application.
Example

If you examine our DefaultController class,


you’ll observe that the Default route is used
multiple times when specifying the route
template for the action methods. The
following code snippet shows how you can
specify different route attributes at the
controller level to make more flexible use of
attribute routing.
Student List Example
In Model add this
Controller
View

Create New View


Create Students
Add the following code to student controller
In th View
In Controller add to receive saved data
Introduction to
Entity Framework
Core
Entity Framework Core
● I am going to give you an overview of Entity Framework Core. The Entity Framework Core which is also
known as EF Core is the latest version of Entity Framework and completely rewrites from the ground up.
As part of this class, we are going to discuss the following pointers.
● What is Entity Framework Core?
● What is ORM?
● Why do we need to use an ORM?
● EF Core Development Approaches.
● EF Core Code First Approach
● Entity Framework Core Database First Approach
● EF Core Database Providers
● Why need to use Entity Framework Core over EF 7.x?
What is Entity Framework Core?

● Entity Framework (EF) Core is an ORM (Object-Relational Mapper) Framework for data access in .Net. It
was released along with .NET Core and is an extensible, lightweight, Open Source, and cross-platform
version of Entity Framework data access technology. It works on multiple operating systems like
Windows, Mac, and Linus.
What is ORM?
● The term ORM stands for Object-Relational Mapper and it automatically creates classes
based on database tables and the vice versa is also true. That is, it can also generate the
necessary SQL to create the database based on the classes.

● As a developer, we mostly work with the application business objects and the ORM
Framework generates the necessary SQL (to perform the CRUD operation) that the
underlying database can understand. So, in simple words, we can say that the ORM
Framework eliminates the need for most of the data access code that as a developer we
generally write.
Why do we need to use an ORM?
● Let us understand why we need to use the ORM Framework with an example.

● Suppose we want to develop an application to manage the students of a college. In order to do this, we
may need to create classes such as Student, Department, Address, etc. Technically we called these
classes as Domain classes.
● Without using ORM Framework like Entity Framework or EF Core, we have to write lots of data access
code to perform the CRUD operations i.e. store and retrieve the Student, Department and Address data
from the underlying database tables.
● For example, in order to perform CRUD operations i.e. read, insert, update or delete from a database
table, we generally need to write custom code in our application to generate the required SQL
statements which can be understood by the underlying database. Again, when we want to read the data
from the database into our application, then also we have to write some custom code to map the
database data to our model classes like Student, Department, Address, etc. This is a very common task as
a developer for us that we do almost in every application.
● An ORM Framework like Entity framework or EF Core can do all of the above for us and saves a lot of
time if we provide the necessary required information to the ORM Framework. The ORM Framework sits
between our application code and the Database. It eliminates the need for most of the custom
data-access code that we usually write without an ORM.
Cont..
EF Core Development Approaches:
● Entity Framework Core supports two development approaches. They are as follows:
● Code-First Approach
● Database-First Approach
● EF Core mainly targets the code-first approach and provides little support for the database-first
approach at the moment.

● EF Core Code First Approach:


● In the EF Core Code First Approach, first, we need to create our application domain classes such
as Student, Branch, Address, etc. and a special class that derives from Entity Framework
DbContext class. Then based on the application domain classes and DBContext class, the EF Core
creates the database and related tables.
Cont..

● Out of the box, in the code-first approach, the EF Core API creates the database and tables
using migration based on the default conventions and configuration. If you want then you
can also change the default conventions used to create the database and its related tables.
This approach is useful in Domain-Driven Design (DDD).
EF Core Database First Approach:

● If you have an existing database and database tables are already there, then you need to
use the EF Core Database First Approach. In the database-first approach, the EF Core
creates the DBContext and Domain classes based on the existing database schema using EF
Core Command.
EF Core Database Providers:

● The EF Core supports both relational and non-relational databases and this is possible due
to database providers. The database providers are available as NuGet packages. The
Database Provider sits between the EF Core and the database it supports.
Required Packages
DbContext in Entity Framework Core
● What is a DbContext class?
● The DBContext class is basically used by our application to interact with the underlying database.
That means this class is used to manage the database connection as well as also used to perform
CRUD operation with the underlying database.

● How to create and use the DbContext class in Entity Framework Core?
● In order to use the DbContext class in your application, you need to create a class derives from
the DbContext class. The DbContext class present is
in Microsoft.EntityFrameworkCore namespace.
Cont..
● The DbContext in Entity Framework Core perform the following tasks:
● Manage database connection
● Configure model & relationship
● Querying database
● Saving data to the database
● Configure change tracking
● Caching
● Transaction management


● The DbContext

public class StudetsDBContext : DbContext


{

public StudetsDBContext(DbContextOptions<StudetsDBContext> options) : base(options)


{

}
public DbSet<Students> students { get; set; }

App setting —

"ConnectionStrings": {
"dbcon": "Server=.;database=testdb;Trusted_Connection=True;TrustServerCertificate=True;"
}
Controller
1. private readonly StudetsDBContext _context;
2.
3. public usersController(StudetsDBContext context)
4. {
5. _context = context;
6. }
7. —-----------------
8. Index
9. public IActionResult Index()
10. {
11. var students=_db.students.ToList();
12.
13. return View(students);
14. }
15.
16.
Index
Conn
public IActionResult Details(int id)
{
var students = _db.students.Find(id);
return View(students);
}
—-------------------
public IActionResult Create()
{

return View();
}
—-------------
[HttpPost]
public IActionResult Create(Students students)
{
_db.students.Add(students);
_db.SaveChanges();
return RedirectToAction("Index");
}
In the Create
View
Edit

public IActionResult Edit(int id)


{
var students = _db.students.Find(id);
return View(students);
}
[HttpPost]
public IActionResult Edit(Students students)
{
if(students == null)
{
return View(students);
}
if (ModelState.IsValid)
{
_db.students.Update(students);
_db.SaveChanges();
return RedirectToAction("Index");
public IActionResult Delete(int id)
{
var students = _db.students.Find(id);

return View(students);
}
[HttpPost]
public IActionResult Delete(Students students)
{

_db.students.Remove(students);
_db.SaveChanges();
return RedirectToAction("Index");
}
What is ViewBag in ASP.NET Core MVC?
ViewBag is a dynamic property of the Controller base class. The dynamic type is introduced in C#
4.0. It is very much similar to the var keyword that means we can store any type of value in it but the
type will be decided at run time rather than compile-time.

The ViewBag :transfers the data from the controller action method to a view only, the reverse
is not possible.

How to Pass and Retrieve data From ViewBag in ASP.NET Core MVC?

The point that you need to keep in mind is, ViewBag is operating on the dynamic data type. So we don’t
require typecasting while accessing the data from a ViewBag. It does not matter whether the data that we
are accessing is of type string or any complex type.
ViewBag in ASP.NET Core MVC with String
Type:
ViewData in ASP.NET Core MVC Application
The ViewData in ASP.NET Core MVC is a dictionary of weakly typed objects which is derived from the
ViewDataDictionary class.

What is the use of ViewData?

1. ViewData is used to pass the data from the controller action method to a view and we can
display this data on the view.
2. The ViewData is work on the principle of Key-value pairs. This type of binding is known as
loosely binding.
3. We can pass any type of data in ViewData like normal integer, string, even though you can
pass objects.
4. ViewData uses the ViewDataDictionary type.
How to use ViewData?
First, we need to create a new key in ViewData and then assign some data to it. The
key should be in string format and you can give any name to it and then you can
assign any data to this key.

ViewData[“KeyName”] = “Some Data”;

Since ViewData is a server-side code, hence to use it on view, we need to use the
razor syntax i.e. @

@ViewData[“KeyName”]
DataAnnotations
is used to configure your model classes, which will highlight the most commonly
needed configurations.

Data annotation in ASP.NET Core refers to the process of labeling the data that an
application deal with.

In other words, data annotations are attributes that are added to the properties which
will let you enforce data input restrictions that might be necessary
System.ComponentModel.DataAnnotations
includes
the following attributes that impacts the nullability or size of the column.

Key
Required
MinLength
MaxLength
StringLength
Timestamp
ConcurrencyCheck

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy