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

WebAPI Core

The document discusses several topics related to ASP.NET Core including onion architecture, the request pipeline in web APIs, the core pipeline, routing, middleware, services, and controllers. It provides details on how requests flow from the browser or IIS to middleware to routing to controllers. Key components in the pipelines include HTTP servers, message handlers, routing dispatchers, and controller dispatchers.

Uploaded by

Akash Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

WebAPI Core

The document discusses several topics related to ASP.NET Core including onion architecture, the request pipeline in web APIs, the core pipeline, routing, middleware, services, and controllers. It provides details on how requests flow from the browser or IIS to middleware to routing to controllers. Key components in the pipelines include HTTP servers, message handlers, routing dispatchers, and controller dispatchers.

Uploaded by

Akash Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Contents

---What is onion Architecture................................................................................................................2


---WEB API Pipe Line..............................................................................................................................2
---Core Pipe Line....................................................................................................................................3
---Asp.net Mvc request pipeline?..........................................................................................................3
---Explain Rest Principle.........................................................................................................................3
---How server know request from browser is from Mvc or Webapi?....................................................4
---What is webapi..................................................................................................................................4
---What is asp.net core..........................................................................................................................5
---What are the benefits of using ASP.NET Core over ASP.NET.............................................................5
---What AddTransient, AddScoped and AddSingleton Services Differences..........................................6
---What is requirement of Start working on .net Core Web API............................................................6
---What is structure of CORE WEB API Application................................................................................6
---What is the use of the Configure method of startup class.................................................................9
---What is Middleware...........................................................................................................................9
---What is the use of "Map" extension while adding middleware to ASP.NET Core pipeline..............10
---What is Request delegate?..............................................................................................................10
---What is Host in ASP.NET Core..........................................................................................................11
---What is routing in ASP.NET Cor........................................................................................................11
---How ASP.NET Core serve static files.................................................................................................12
---Explain Session and State management in ASP.NET Core................................................................12
---How to enable Session in ASP.NET Core..........................................................................................12
---What are the various JSON files available in ASP.NET Core.............................................................13
---What is tag helper in ASP.NET Core?...............................................................................................13
How to disable Tag Helper at element level?......................................................................................14
---What is CORS...................................................................................................................................14
---Dependency injection in ASP.NET Core............................................................................................14
---What's Dapper?...............................................................................................................................14
Write a query to perform CRUD operations........................................................................................14
---DbContext........................................................................................................................................15
---Deference between REST and SOA?................................................................................................15
---What is Dot net core Web API and Dot net Web API?.....................................................................15
---Deference between ADO.net and Entity Frame work......................................................................15
---Difference between code first approach, data base first approach.................................................16
---What is the function name for allocating the memory for ConnectionContext class.......................16
---What is end point.............................................................................................................................16
---What is owin....................................................................................................................................17
---What is Kestrel.................................................................................................................................17
---What is migration?...........................................................................................................................17
---For connecting dotnet core to database we need two packages.....................................................17
---What is Metapackages.....................................................................................................................17
---What is the basic knowledge for Core Web API...............................................................................17
---What is default return type of .net core api....................................................................................17
---What is default return type of .net api?...........................................................................................18
---Web API content negotiation...........................................................................................................18
---How can improve the performance of API? There are 8 ways we can improve...............................18
---What is IConfiguration.....................................................................................................................19

---What is onion Architecture?


Onion Architecture also known as clean Architecture.it was written in 2008. It is just design guide
line. It supports DIP and cohesion principle. It provides loose coupling architecture and separation of
concern. There are several layers when we creating onion Architecture like that domain,
infrastructure, service, UI. Domains defines Entity’s and entity represent tables. infrastructure layer
follows repository pattern. Service is business logic layer.

---WEB API Pipe Line


Request comes from IIS to Controller. Whenever user request to API controller request comes first
to Httpserver class. Httpserver class initialize Http Request and Http Response once it
done than forward request to Massage Handlers class also known as delegating handler class.
combination of multiple massage handlers is set to be delegating handler. Massage Handlers place a
measure role in API Request Pipe line. Massage Handlers class act as middle ware for the controller.
Every request made by the browser for the controller Massage Handlers act as middle ware between
IIS and the Controller. By the Massage Handlers we enable caching. We can also apply security
related like authentication and authorization and token authentication in Massage Handlers.
Massage Handlers secure our end point. Than request move to Router Dispatcher. Router Dispatcher
checks your requested end point means route is available in rout table or not. If it is not available in
rout table, it checks at attribute routing. Once it finds request rout in attribute routing then they
don’t go to check in conventional routing. Than routing dispatcher class forward request to
controller dispatcher class. controller dispatcher class instantiate the controller class. the role of
controller dispatcher class is creating an object of controller class. once controller class instantiated
so controller dispatcher class internally create an object of controller class. than we can achieve
dependency injection. Than your function of your controller will be called. controller dispatcher and
Massage Handlers class place a measure role in case of WEB API.
There are five important class place a measure role in Request pipe line of WEB API
1-Http Server, 2-Http request and
Http Response, 3-Massage Handler ,
4-Routing Dispatcher, 5-Controller
Dispatcher, 6-Controller

---Core Pipe Line


First of all core based application runs over the kestrel server. This is the self-hosting server. This is
the local server for boot the application and runs local with the localhost port number. If you go for
IIS or other server deployment request moves from browser to IIS. And IIS can forward the request
to kestrel server. Kestrel Server never gives you public IP Address it gives your local IP address.
There is one module in IIS who responsible for forwarding request to kestrel server its call
AspNetCoreModuleV2.when kestrel receive the request from IIS it forward the request to Main
function. Main is entry point. Main function forward the request to startup.cs file. Startup.cs file
forward the request to Configure function. Configure function is middle ware. Configure function
forward the request to Configure Services function. Configure is HTTP pipe line for the core based
application. After Configure Services function finally comes end point Controller.

1-IIS, 2-AspNetCoreModuleV2,
3-Kestrel server, 4-Main function,
5-Startup.cs, 6-Configure Function,
7-Configure Services , 8-Controller.

---Asp.net Mvc request pipeline?


Mvc is based on IIS. How request goes from browser to IIS this is call Application life cycle and how
request move from IIS to Mvc this call Mvc request pipeline. Mvc is based on rout table architecture.
request First come on 1-URLRoutingModule. Every request on mvc pipe line
URLRoutingModule catch request first. It takes the requested URL and scene URL in 2-
routetable if URL available in routTable it forward the request to
3-RoutHandler. RoutHandler forward request to MvcHttpHandler. 4-
MvcHttpHandler class internally implement the interface 5-IHttpHandler.
IHttpHandler interface having a function 6-ProcessRequest.
ProcessRequest Is the entry point for the Mvc controller.

IIS Server 1-URLRoutingModule


2-Routetable 3-RoutHandler
4-MvcHttpHandler 5-IHttpHandler
6-ProcessRequest

---Explain Rest Principle.


REST is a set of principles that define how Web standards, such as HTTP and URIs, are supposed to
be used. There are five important REST principle as given below –

Addressable Resources - Each resource should be identified by a URI (unique identifier)

Simple and Uniform Interfaces - REST is based on HTTP protocol so use HTTP GET, POST, PUT and
DELETE method to perform actions. This make REST simple and uniform.
Representation Oriented- Representation of resources are exchanged. GET is used to return a
representation and PUT, POST passes representation to the server so that underlying resources may
change. Representation may be in many formats like XML, JSON etc.

Communicate Stateless - An application may have state but there is no client session data stored on
the server. Any session specific data should be held and maintained by the client and transferred to
the server with each request as needed.

Cacheable - Clients should be able to cache the responses for further use.

---How server know request from browser


is from Mvc or Webapi? RoutTable is responsible for understading
the request. Webapi routtable follow UNIformate architecture Rest. Where Mvc don’t follow
UniFormate Rest. In rest api only controller name and Verbs Required.

How routtable create in webapi?


---What is webapi?
Existing web api is tightly coupled with IIS server. And IIS is only for windows. IIS only runs on
windows platform.
---What is asp.net core?
who follow REST principle this set to be Restful services. Core is completely written of existing
webapi. If you developing core based application, there is no need IIS. Core follow Owin (Open Web
Standard) Architecture. Web API is used for making REST full service. It a HTTP service. Core is
product of Microsoft it is primary meant for cross platform, it is open source and support across all
platform. it has not dependencies with the operating system like windows.it has not dependency
over the IIS. You can install this software in an any operating system. The Best part is it runs self-
hosting server. It has own server for developing the applications. Its call kestrel server. It just a
development server. kestrel is not full fledge server like IIS. Local server never gives you public IP
address. It just for development. Production server it could be IIS, Apache, MGX server for Ubuntu.
Asp.net core is cross-platform, high-performance, open-source framework for building modern,
cloud-based, internet-connected application. It is redesign from ground up of previous version of
asp.net. Don’t try to compare with Kestrel and IIS server. Because local server never gives you public
IP address. That’s why kestrel is not internet facing server. It just local server. Kestrel is just for local
IP address. And for only local host. If you want to publish or deploy than IIS forward the request to
Kestrel and kestrel forward the request to application. we don’t directly host application on IIS
server or any server. We host on Kestral and kestrel host to IIS server or any other server. There is
one module on IIS server call ASPnetcoreModule. It is basically library. This module plays a measure
role. You need to install this library from Microsoft on IIS. IIS forward request to kestrel responsible
is ASpnetcoremodule. most important things is kestrel is written in node.js. so there is no
dependency. Over any IIS or any kind of server.
-It can develop and run across deferent platform like windows, macos, Linux.
-Asp.net can be host only on IIS but core can be host IIS, Apache, Docker, self-host in your own
process. –Built in supports for
dependency injection. -Cloud-Based Web Application
Development Support. -Introduced new, fast and cross-platform web server -
Kestrel. So, a web application can run without IIS, Apache, and Nginx. -
Command-line supports to create, build and run the application -There is no web.config
file. We can store the custom configuration into an appsettings.json file
-There is no Global.asax file. We can now register and use the services into startup class
-It has good support for asynchronous -Provide
protection against CSRF (Cross-Site Request Forgery) If your application
(web/service) needs to run on multiple platforms (Windows, Linux, and mac OS), use .NET Core.
.NET Core supports the previously mentioned operating systems as your development workstation.
Visual Studio provides an Integrated Development Environment (IDE) for Windows and mac OS. You
can also use Visual Studio Code, which runs on mac OS, Linux, and Windows. Visual Studio Code
supports .NET Core, including IntelliSense and debugging. API is
platform dependent and server dependent. But core is not.

---What are the benefits of using ASP.NET


Core over ASP.NET?
Cross platform, provide ability to develop and run on Windows, Linux and MacOS.

Open-source
Unified Platform to develop Web UI and services.

Built-in dependency injection.

Ability to deploy on more than one server like IIS, Kestrel, Nginx, Docker, Apache etc

cloud enabled framework, provide support for environment based configuration system.

Lightweight, High performance and modern HTTP request pipelines.

well suited architecture for testability

Integration of many client-side frameworks like Angular any version

Blazor allow you to use C# code in browser with JavaScript code.

---What AddTransient, AddScoped and


AddSingleton Services Differences?
AddTransient if we are using
addtransient it provides new instance on each request whether it is in the scope of the same http
request or across different http request. Means it create new object on each request.

AddScoped When we register a type as Scoped, one instance is available throughout the application
per request. When a new request comes in, the new instance is created. Add scoped specifies that a
single object is available per request.

AddSingleton with a singleton service,


a there is only a single instance created. When the service is first time requested and that single
instance is used by all http requests throughout the application. it means only first time object will
be creating and after that all request use same object.

---What is requirement of Start working


on .net Core Web API? First Need to install dot net core
1-https://dotnet.microsoft.com/download/dotnet-core/3. 2-Sql server
any version 3-Editor Visual Code

---What is structure of CORE WEB API


Application?
-Controller with the help of
controller we can make the end point, what is end point. With the help of end point, we can
communicate. It gives you privileges how we can make an end point. End point How communicate
you as address. –Chahe mvc Controller ho ya web api ka controller ho
controller se end point banta hai aur page se url banta hai. Controller se route banta hai.
-appsetting.json Within this file we
provide the connection string there is no config file in the core web api application.

-Applicationname.csproj This is the most


important file in application core by this file we can take an any reference of packages for Entity
framework. Packages of Ado net library packages. Packages for token authentication. There are
several packages call library.

-Statrtup.cs Startup class is the entry


point of the ASP.NET Core application. Every .NET Core application must have this class. This class
contains the application configuration related items. It is not necessary that class name must
"Startup", it can be anything, we can configure startup class in Program class.
ConfigureServices and Configure are called by the ASP.NET Core runtime when the app starts:
this file is core of core web api this file play measure role for developing the restful api known as
service. We can make service our we can consume multiple application. In this file there are 2
function

Cunfigureservices(IServiceCollection)

This method calls first when the application is requested for the first time. Using this method, we can
add the services to the DI container, so services are available as a dependency in controller
constructor.

Ye function Startup(IConfiguration configuration) constructor k call hone k baad call hota hai. yaha
par hum apne configuration ko likhte hai. Appsetting configuration Connection string setting, CORS
configuration, Dependency injection, humare project se related configuration hum isi function me
karte h. Application level configuration task we apply in this function like calling the connection
string using appseting. Q k function me IServiceCollection interface hota hai aur is interface me
several method hote hai application setting se related. Jitne bhi use hum ConfigureServices()
function me karenge. by this function we
can configure Entity framework this function support inbuilt IOC container for auto instantiation of
the class without writing a new operator to support dependency injection. As we do by as provider
in angular components. Cunfigureservices
function k dwara hum IOC call karte hai. Ye internally IOC container ko support karta hai. What is IOC
container? It provides inbuilt auto instantiation

-Cunfigure(IApplicationBuilder app, IWebHostEnvironment env) This function will help


you to communicate with the controller to getting the end point. Controller ki maping configure
function me hoti hai. This function act as middleware. We can also achieve token authentication by
this function.
-We initialize entity framework in this file. -Jo global.asax file
MVC aur asp.net me kaam karta tha wahi kaam core me Startup.cs karta hai.

function- Rout table is defined within this function. Authentication, Authorization, Token, Filters,
Action Filters, Custom Middleware. this IApplicationBuilder has having several
extension methods and out of that method to enable the authentication for the securing the end
point.ye IWebHostEnvironment interface hosting se related setting provide karata hai. Jitne bhi
security se related setting honge use hum Configure() function me karenge. Configure() method
same waise hi kaam karta hai jaise ki asp.net me httpmodule karta hai. Jaise asp.net me har request
Httpmodule ko cross karta hai waise hi core me har request Configure() function ko cross karega.
Jaise asp.net k end point ko secure Httpmodule karta hai same waise hi core me action filter karega
aur action filter Configure() function me configure hoga.

How request has gone browser to controller –Step 1


Program.cs –Step 2 Startup.cs
–Step 3 Middleware –Step 4
Controller

Whenever user request to Core web api and Core Mvc it does not matter they have the common
architecture. They have the common life cycle. Request first goes to program.cs. isi file me Kestral
kaise configure hoga uske syntax likhe hue hai. Yaha se server start hota hai. Jaise hi server start hota
hai next file comes Startup.cs is file me 2 function hota hai configureservice() aur configure. Comes in
figure function connecting to the controller by the rout table or we can go for the attribute routing.

Program.cs this file consists of main


function and main is entry point. Main is entry point for the application. Program.cs attached with -
start.cs. kestrel server isi file me configure hota h. kyu k yehi par main function hota h. program.cs
file same global.asax file ki tarah hota h. jaise mvc aur asp.net me hota hai. Isliye application yehi se
start hota h. aur main function request karta h startup class ko.

Note- Jab hum core application ko start karte h to application start program.cs file se hota h.
program.cs file Main static function call hota hai. Main () function call karta h static
CreateHostBuilder function ko. Startup.cs file me Startup name se class hota h. is class me 2 function
hote hai. ConfigureServices () aur Configure (). ConfigureServices () function IServiceCollection
Interface as parameter leta hai. Configure () function IApplicationBuilder aur IWebHostEnvironment
as Interface parameter leta hai. Jab core application start hota h to ConfigureServices () aur
Configure () function ko cross jarur karta hai. uske baad end point par jata hai. End point Configure ()
function me likha hota ha using rout table.

---What is the use of the Configure method


of startup class? It defines how the application will respond to
each HTTP request. We can configure the request pipeline by configuring the middleware. It accepts
IApplicationBuilder as a parameter and also it has two optional parameters: IHostingEnvironment
and ILoggerFactory. Using this method, we can configure built-in middleware such as routing,
authentication, session, etc. as well as third-party middleware.

---What is the difference between IApplicationBuilder.Use() and IApplicationBuilder.Run()?


We can use both the methods in Configure methods of startup class. Both are used to add
middleware delegate to the application request pipeline. The middleware adds using
IApplicationBuilder.Use may call the next middleware in the pipeline whereas the middleware adds
using IApplicationBuilder.Run method never calls the subsequent or next middleware. After
IApplicationBuilder.Run method, system stop adding middleware in request pipeline.

---What is Middleware?
If someone request to my end point. I want to inject certain code. That code be triggered first. This is
call middleware. We have inbuilt middleware we can call by use function. Use is overloaded
function. if you want go for routing use. Use mvc. Want go for exception filter use. These are the
inbuilt middleware. Use basically used for inbuilt middleware. Every inbuilt middleware hook-up
through use function. use is Extension method of IApplicationBuilder. Every request in core
application should be crossed by configure function. Configure is inbuilt function and this function
takes parameter IApplicationBuilder and IWebHostEnvironment. IApplicationBuilder is and interface
and this gives you inbuilt middleware like exception, filter.

If we want to make custom middleware and want to hook-up them. Than we need to use
RequestDelagte. We can call those function which signature matches with the delegate. It takes
single parameter. Return type of this function is Task. Agar kissi heavy function ko deferent thread
par run karna chahte ho to uske pehle task lga do. task se ek naya thread generate hota hai. Function
jaise hi execute hoga wo thread automatic release ho jayega. Use function se inbuilt middleware call
hoga our usemiddleware se costum middleware function call karte hai. Usemiddleware me hum
apne function ka name de sakte hai. Hum apne custume middleware ko call karne kliye
usemiddleawre me apne custom middleawrae k class ka name pass karte hai.

It is software which is injected into the application pipeline to handle request and responses. They
are just like chained to each other and form as a pipeline. The incoming requests are passes through
this pipeline where all middleware is configured, and middleware can perform some action on the
request before passes it to the next middleware. Same as for the responses, they are also passing
through the middleware but in reverse order.
---What is the use of "Map" extension while
adding middleware to ASP.NET Core
pipeline? It is used for branching the
pipeline. It branches the ASP.NET Core pipeline based on request path matching. If request path
starts with the given path, middleware on to that branch will execute.

---What is Request delegate?


Request delegates handle each HTTP request and are used to build request pipeline. It can
have configured using Run, Map and Use extension methods. A request delegate can be an in-line as
an anonymous method (called in-line middleware) or a reusable class. These classes or in-line
methods are called middleware components.

---How to read values from Appsettings.json file?

class Employee {

// requires using Microsoft.Extensions.Configuration;

private readonly IConfiguration Configuration;

public Employee (IConfiguration configuration)

{
Configuration = configuration;

// public void ReadValues(){

var val = Configuration["key"]; // reading direct key values

var name = Configuration["Employee:Name"]; // read complex values

---What is the Options Pattern in ASP.NET Core? Options


Pattern allow you to access related configuration settings in Strongly typed way using some classes.
When you are accessing the configuration settings with the isolated classes, The app should adhere
these two principles.

Interface Segregation Principle (ISP) or Encapsulation: The class the depend on the configurations,
should depend only on the configuration settings that they use.

Separation of Concerns: Settings for different classes should not be related or dependent on one
another.

---What is Host in ASP.NET Core?


Host encapsulates all the resources for the app. On startup,
ASP.NET Core application creates the host. The Resources which are encapsulated by the host
include:

HTTP Server implementation

Dependency Injection

Configuration

Logging

Middleware components

---What is routing in ASP.NET Core?


Routing is used to handle incoming HTTP requests for the app. Routing find matching executable
endpoint for incoming requests. These endpoints are registered when app starts. Matching process
use values from incoming request url to process the requests. You can configure the routing in
middleware pipeline of configure method in startup class. There are two types of routing
supported by ASP.NET Core

The conventional routing

Attribute routing

The Routing uses routes for map incoming request with route handler and Generate URL that used in
response. Mostly, the application having a single collection of routes and this collection are used for
the process the request. The RouteAsync method is used to map incoming request (that match the
URL) with available in route collection.

---How ASP.NET Core serve static files?


In ASP.NET Core, Static files such as CSS, images, JavaScript files, HTML are the served directly to
the clients. ASP.NET Core template provides a root folder called wwwroot which contains all these
static files. UseStaticFiles() method inside Startup.Configure enables the static files to be
served to client.
You can serve files outside of this webroot folder by configuring Static File Middleware as following.

app.UseStaticFiles(new StaticFileOptions

FileProvider = new PhysicalFileProvider(

Path.Combine(env.ContentRootPath, "MyStaticFiles")), // MyStaticFiles


is new folder

RequestPath = "/StaticFiles" // this is requested path by client

});

// now you can use your file as below

<img src="/StaticFiles/images/profile.jpg" class="img" alt="A red rose" />

// profile.jpg is image inside MyStaticFiles/images folder

---Explain Session and State management


in ASP.NET Core As we know HTTP is a
stateless protocol. HTTP requests are independent and does not retain user values. There are
different ways to maintain user state between multiple HTTP requests.

Cookies

Session State

TempData

Query strings

Hidden fields

HttpContext.Items

Cache

---How to enable Session in ASP.NET Core?


The middleware for the session is provided by the package Microsoft.AspNetCore.Session. To use
the session in ASP.NET Core application, we need to add this package to csproj file and add the
Session middleware to ASP.NET Core request pipeline.
---What are the various JSON files
available in ASP.NET Core? There are following
JSON files in ASP.NET Core :

global.json

launchsettings.json

appsettings.json

bundleconfig.json

bower.json

package.json

---What is tag helper in ASP.NET Core?


It is a feature provided by Razor view engine that enables us to write server-side code to create and
render the HTML element in view (Razor). The tag-helper is C# classes that used to generate the
view by adding the HTML element. The functionality of tag helper is very similar to HTML helper of
ASP.NET MVC.
How to disable Tag Helper at element level?
We can disable Tag Helper at element level using the opt-out character ("!"). This character must
apply opening and closing the Html tag.

---What is CORS? Cross-


Origin Resource Sharing (CORS) manages the cross-origin requests. Unlike same-origin policy, CORS
allows making a request from one origin to another. CORS allows the servers to specify who can
access the resource on the server from outside.

---Dependency injection in ASP.NET Core?


ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique
for achieving Inversion of Control (IoC) between classes and their dependencies.
Dependency Injection is a Design Pattern that's used as a technique to achieve the
Inversion of Control (IoC) between the classes and their dependencies.
ASP.NET Core comes with built-in Dependency Injection framework that makes configured services
available throughout the application. You can configure the services inside ConfigureServices
method as below. A Service can be resolved using constructor injection and DI framework is
responsible for the instance of this service at run time.

---What's Dapper?
Dapper is a simple object mapper for .NET and owns the title of "King of Micro ORM" in terms of
speed. An ORM is an Object Relational Mapper, which is responsible for mapping between database
and programming language.
There are three steps to working with Dapper as follows,

Create an IDbConnection object.

Write a query to perform CRUD


operations.
Pass query as a parameter in Execute methodk.

---DbContext
DbContext class represents a session with a database and provides an API for communicating with
the database. DbContext is responsible for opening and managing connections to the database.
---Deference between REST and SOA?
If you go for SOA our Rest ultimate goal is to create a service. What is service? Service is meant for
achieving distribute architecture. There are several service which we can create like WCF, web
service, soap service. But these are coming under SOA.
-SOA stands for service oriented architecture and REST is representasnal state transfer If we are
making service using by SOA than we can’t access by the browser.
–SOA we can only access by JavaScript, MVC or asp.net. we can access the data directly by the
browser. –SOA is SOAP based service. Soap
stand for simple object access protocol. –In SOAP based service request is send via
envelope. Envelope support xml. And receiver also receive via envelop. It means sender and receiver
both can communicate via envelop. This is call soap request and soap response. –It
is tight coupling means sender and receiver should support SOAP. -REST support
http request rather than SOAP request. Means REST support Http request and Http response.
–REST send request via http body. It means we need just browser and we can communicate with
each other via browser no need and kind of software for communicating to each other.

---What is Dot net core Web API and Dot


net Web API? -Core web API is has having own server.it
called kestrel working points of view is quite deference to web API. There is not comparison between
at all. –Data access layer is quite similar.
-Business logic is quite similar. -Web api is
restful service. What is restful service. If any service gives a data directly by the protocol in Jason
format it is set to be rest full service. –We api is HTTP service that’s why we can
directly access by the browser. But by the browser we can’t post the data or update the data.
–both web api and web api core HTTP request and HTTP response. –WEB api
never runs over deferent operating system. It only for windows. –
WEB Api never runs over the deferent server. Like Tom cat, Ubuntu, MGX, Apache server.
–Core k application IIS server par nahi chalte ye self-hosted server par chalet hai ise kestrel kahete
hai. Kestrel self-hosting server hota hai core web based application k liye. Wo chahe core mvc ho ya
core web api. Jabki webapi sirf IIS par chalet hai.
–Kestrel server kewal development k liye hota hai production k liye nahi. isse node.js me likha gaya
hai. Ye open source hai aur kisi bhi operating system par chal sakta hai.

---Deference between ADO.net and Entity


Frame work? -Entity framework is a product of Microsoft.
Which follow orm principle. Link q also orm based. EF gives you privileged you can communicate to
the database by two ways code first approach, data base first approach.
–EF is ORM based principle. And ado is relational database based. ORM object relation management.

---Difference between code first approach,


data base first approach? -Database first approach me
database pehle hoga then table class banegi.
–Code first approach me class convert into a table. Database first approach Table convert into class.

---What is REST? REST stands for


Representational State Transfer. This is a protocol for exchanging data over a distributed
environment. REST is an architectural style which treat each service as a resource and access data by
HTTP protocol methods like GET, POST, PUT, and DELETE.

REST-style architectures consist of clients and servers. Clients initiate requests to servers who
process these requests and return responses based on these requests. These requests and responses
are built around the transfer of representations of these resources.

---What is the function name for allocating


the memory for ConnectionContext class?
The function name is AddDbContext ye function internally ConnectionContext class k memory ko
allocate karega tab tb parametrize constructor call hoga then use waha dbContextOptions milega.

Dotnet ef migrations add test

---DbContextOptions –This class point to


connection string.

---DbContect –This point to


database

---DbSet –This point to tables

---AddDbContext -addDbcontext
function is generic function this function will help you for create instance of the connection class.
Then you will be pointing to be connection string.

---What is end point?


How we can request to you. Matlb request server se application tak kaise ata hai use hi end point
kehte hai jaise ki kisi application ka Url –www.ICC-Cricket.com hai. Ab server se request is url tak
kaise aya hai use hai end point kehte hai. End point basically Url hota hai. Core web api gives you end
point. End point is basically a url. It is controller + action.
www.ICC-Cricket.com/controller/action -Jab tak controller class controllerBase class
se inherit nahi hoga tab tak end point nahi banega. Isi class k pas Http verbs ka support hi. Http
routing ka support hai. Namespace Microsoft.AspNetCore.Mvc;

---What is owin?
Owin is kind of package or library. It is inbuild by default in any kind of core version. Owin gives you
two file program.cs and startup.cs. Owin is an inbuilt middleware between kestrel server and
application end point (url). Owin is just api it lies between self-hosted server like kestrel and web api
end point. Core mvc aur core web api dono k pass inbuild middleware Owin hota hai. Defrence ye
hai ki mvc k pas view aur data hota hai aur api k pass sirf data hota hai. Q k ye service hai.Owin is
inbuilt api which provide communication between kestrel and webapi. Owin server aur api k bich
bridge ka kaam karta hai.

---What is Kestrel?
Kestrel ek development server hai. ye self-hosted server hota h. ye real server nahi hota it available
in context of developing the api core and mvc core application. Ye node.js framework me likha hota
hai aur kisi bhi framework par chal sakta hai.

---What is migration?
After configuring the connection, we can do migration. Migration is technique in to create a
database and table dynamically in case of code first approach. Isse database banega. Code first
approach se database ka deployment easy ho jata hai.

---For connecting dotnet core to database


we need two packages?
1 dotnet add package Microsoft.entityframworkcore.sqlserver

---What is Metapackages?
The framework .NET Core 2.0 introduced Metapackage that includes all the supported package by
ASP.NET code with their dependencies into one package. It helps us to do fast development as we
don't require to include the individual ASP.NET Core packages. The assembly
Microsoft.AspNetCore.All is a meta package provide by ASP.NET core.

---What is the basic knowledge for Core


Web API? Generics, Collections, Interface, Task parallel library,
Abstract class, Inheritance, Runtime polymorphism class all these of c#

---What is default return type of .net core


api? default Web API returns result in
XML format. ... If client need data in JSON format then type=json and same
way if it is XML then type=xml, Here is the complete code you need to add in
WebApiConfig

---What is default return type of .net api?


By default, Web API returns result in XML format. If client need data in JSON
format then type=json and same way if it is XML then type=xml, here is the
complete code you need to add in WebApiConfig
---Web API content negotiation
“Content Negotiation” means the client and server can negotiate. It’s not always possible for the
server to return data in the requested format. That’s why it’s called negotiation, not demand.

In web API we request and API give response but it doesn’t provide the same response that we need
every time so that’s why it is called content negotiation.

● Content-type: which request to API to represent data in this type.

● Accept: The acceptable media types for the response, such as “application/json,”

“application/xml,” or a custom media type such as "application/vnd.example+xml".

● Accept-Charset: The acceptable character sets, such as UTF-8 or ISO 8859-1.

● Accept-Encoding: The acceptable content encodings, such as gzip.

● Accept-Language: The preferred natural language, such as “en-us”.

---How can improve the performance of


API? There are 8 ways we can improve.
There are 8 ways to improve the performance of wpi.

1 Use fastest JSON serializer JSON serialization can affect


overall performance of ASP.NET Web API significantly. around 20% performance improvement on
my Web API responses

2 Manual JSON serialize from DataReader


Instead reading values from DataReader and populating objects and after that reading again values
from those objects and producing JSON using some JSON Serializer, you can manually create JSON
string from DataReader and avoid unnecessary creation of objects. You produce JSON using
StringBuilder and in the end you return StringContent as the content of your response in WebAPI

3 Use other formats if possible (protocol buffer, message pack) If


you can use other formats like Protocol Buffers or MessagePack in your project instead of JSON do
it.You will get huge performance benefits not only because Protocol Buffers serializer is faster, but
because format is smaller than JSON which will result in smaller and faster responses.

4 Implement compression Use GZIP or Deflate


compression on your ASP.NET Web API.Compression is an easy and effective way to reduce the size
of packages and increase the speed.

5 Use caching If it makes sense, use


output caching on your Web API methods. For example, if a lot of users accessing same response
that will change maybe once a day.If you want to implement manual caching such as caching tokens
of users into memory please refer to my blog post Simple way to implement caching in
ASP.NET Web API.
6 Use classic ADO.NET if possible Hand coded ADO.NET is still
the fastest way to get data from database. If the performance of Web API is really important for you,
don’t use ORMs. You can see one of the latest performance comparison of popular ORMs.
The Dapper and the hand-written fetch code are very fast, as expected, all ORMs are slower than
those three. LLBLGen with resultset caching is very fast, but it
fetches the resultset once and then re-materializes the objects from memory.

7 Implement async on methods of Web API Using asynchronous Web


API services can increase the number of concurrent HTTP requests Web API can handle.
Implementation is simple. The operation is simply marked with the async keyword and the return
type is changed to Task.

[HttpGet]

[Route("GetAllEmployee")]

public async Task<ActionResult<List<Employee>>> GetEmployee()

try

return await _IObject.GetAllEmployaaData();

8 Return Multiple Resultsets and combined results Reduce number of


round-trips not only to database but to Web API as well. You should use multiple resultsets
functionality whenever is possible.
This means you can extract multiple resultsets from DataReader like in the example bellow:

---What is IConfiguration ?
how do we pass that connection string to
the repository so it can create a
SqlConnection object for Dapper to use?
ASP.NET Core introduces a new IConfiguration object which can be injected into other classes.
That injected instance will contain a method called GetConnectionString which we can use to
obtain our connection string from the appSettings.json files. So, let's inject IConfiguration into
our EmployeeRepository like so:
----Unable to configure HTTPS endpoint. No server certificate was specified, and the default
developer certificate could not be found or is out of date
dotnet dev-certs https

------------------ Steps and Configure API Core----------------------


Step- https://dotnet.microsoft.com/download/dotnet-core/3.

Step- Sql server any version

Step- Editor Visual Code

After creating api core project in VS code then we need to do following commands

dotnet new webapi –o Rahul here rahul is project name

dotnet tool install --global dotnet-ef

dotnet add package microsoft.entityframeworkcore --version 3.1.1

dotnet add package microsoft.entityframeworkcorecore.Design --version 3.1.1

dotnet add package microsoft.entityframeworkcore.sqlserver --version 3.1.1

For Dapper

dotnet add package dapper

dotnet add package System.Data.SqlClient

------------------- All Short Cut for .Net Core-------------------------


---For publishing on IIS dotnet publish

---For downloading references if we declare already? dotnet restore

---For to undo this action, dotnet EF migrations add test use 'ef
migrations remove'

---Before migrations command dotnet tool install --


global dotnet-ef

---Then for migrations dotnet ef


migrations add test

---After migrations dotnet ef database


update

---How to check dotnet core version? Dotnet

---How to change drive? F: press enter

---How to add package or for installing EF core?


–dotnet add package Microsoft.entityframeworkcore
---How to create application in Core? dotnet new console -
o Rahul here rahul is project name dotnet new webapi –o Rahul here
rahul is project name dotnet new mvc –o Rahul here rahul is project
name dotnet new webapp –o Rahul here rahul is project name

---How to change folder directory? Cd

---How to back folder? Cd\

---How to make directory? md foldername

---How to open terminal? ctr + ~

---Need to install 2 software via VS code? C# Extensions


13.1 C# IDE Extention for VSCode

---How to check dotnet version? dotnet --version

---How to build dotnet project? dotnet build


dotnet watch run

---How to open project? code .

---How to clear terminal? cls

---How to install dotnet core sdk version 3.1.100? https://dotnet.microsoft.com/learn/dotnet/hello-


world-tutorial/install

---How to run console? dotnet run

---For checking Feature of dotnet? dotnet new

---For checking version dotnet core? dotnet

---How to add c# extension in code? Go extension and add


this two packages Omnisharp and C# Extension.

---For Connecting to database we need four packages. First check your version
dotnet –Version

1 dotnet add package Microsoft.entityframeworkcore 2


dotnet add package Microsoft.entityframeworkcore.sqlserver 3 dotnet add
package Microsoft.entityframeworkcore.tools 4 dotnet add package
Microsoft.entityframeworkcore.design

---Migration

1 dotnet tool install –global dotnet-ef 2 dotnet ef


migrations add Test 3 dotnet ef database update

--How to Create solution in .net core using command? Dotnet new sln
--name ONIONAPPLICATION

You might also like