WebAPI Core
WebAPI Core
1-IIS, 2-AspNetCoreModuleV2,
3-Kestrel server, 4-Main function,
5-Startup.cs, 6-Configure Function,
7-Configure Services , 8-Controller.
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.
Open-source
Unified Platform to develop Web UI and services.
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.
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.
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
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.
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.
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 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.
class Employee {
{
Configuration = configuration;
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.
Dependency Injection
Configuration
Logging
Middleware components
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.
app.UseStaticFiles(new StaticFileOptions
});
Cookies
Session State
TempData
Query strings
Hidden fields
HttpContext.Items
Cache
global.json
launchsettings.json
appsettings.json
bundleconfig.json
bower.json
package.json
---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,
---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.
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.
---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 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.
---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.
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.
● Accept: The acceptable media types for the response, such as “application/json,”
[HttpGet]
[Route("GetAllEmployee")]
try
---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
After creating api core project in VS code then we need to do following commands
For Dapper
---For to undo this action, dotnet EF migrations add test use 'ef
migrations remove'
---For Connecting to database we need four packages. First check your version
dotnet –Version
---Migration
--How to Create solution in .net core using command? Dotnet new sln
--name ONIONAPPLICATION