Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Create .

dot net core application using CLI

Dotnet new console -o Web API

Dotnet new webapi –name webapiprojectname

Status Code:

All HTTP response status code are divided into five categories.

1XX- informational response.

2XX- Successful.

3XX- Redirection.

4XX- Client error.

5XX- Server error.

Frequently used status code

200 – Ok

201- New Resource created

204 – No content (the server processed the request successfully and it is not returning the content.

301- Moved Permanently.

302- Moved temporarily

400- Bad request

404- Not found

401- Not authorize.

405 – Method not allowed (There is HTTPGet, HttpPUT, post if you use other method rather than actual
method then you will get this error).

500 – Internal server error

503 – Service unavailable (ex- down for maintaince)

Launchsettin.json file: -

It has configuration to run the application in development environment.


Host Builder

Host builder is an object and it is used to add some features in the application.

CreateDefaultBuilder Method provides the below functionality (to read the setting, to configure the
setting).

Will get,

 Dependency Injection (DI)


 Configuration
appSetting.json
appSetting.{env}.json
User secrets
Environment variables etc

Logging

Console, Debug, etc.

 public static IHostBuilder CreateHostBuilder()


        {
            return Host.CreateDefaultBuilder().ConfigureWebHostDefaults (webHost
=>
            {
                webHost.UseStartup<Startup> ();
            });
        }

Note: - if you change the name of CreateHostBuilder Method it will be fine if you use some basic
configuration if you use EF core then this method is must. EF core search this method to some default
configuration.

ConfigureWebHostDefaults:

 Provides support for HTTP.


 Set the kestrel server as the web server.
 Enables the IIS integration.
 ETC...

Startup Class

Startup class has two important methods.

 ConfigureServices (To Configure the services and it is optional)


 Configure (To Configure the HttpRequestPipeline, and to configure the middleware)

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace WebAPIDemo
{
    public class Startup
    {

        public void ConfigureServices(IServiceCollection services)


        {

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


        {
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                  await  context.Response.WriteAsync("Hello from .NET core
project.");
                });
            });
        }

    }
}

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace WebAPIDemo
{
    public class Startup
    {

        public void ConfigureServices(IServiceCollection services)


        {
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


        {
            app.UseRouting(); - Enables the routing.
            app.UseEndpoints(endpoints => :- will map the URL to the resource.
            {
                endpoints.MapControllers();
            });
        }

    }
}

ControllerBase : -

The ControllerBase class provides many method and properties to handle the HTTP request.

APIController:-

 Attribute routing requirement.


 Handle the client error i.e. 400 status code.
 Multipart / form-data request interface.
 Bind the incoming data with parameters.

Middleware:-

 Middleware is a piece of code that is used in the HTTP request pipeline.


 An Asp.Net core web application can have n number of middleware.
 Order of middleware matters a lot in the execution.
Examples: - Routing, Authentication, Add exception page, etc.

Custom Middleware:

RequestDelegate : The request delegate handle each HTTP request. Request delegate are
configured using Run, Map, Use extension method.
HttpContext : encapsulates all the Http-specific information.

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace WebAPIDemo
{
    public class CustomMiddleware:IMiddleware
    {
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            await context.Response.WriteAsync("Hello from custom middleware");
        }
    }
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            app.UseMiddleware<CustomMiddleware>();
        }

Run (), Use (), Next () & Map () method in middleware

Run () method is used to complete the middleware execution.

Use () method is used to insert a new middleware in the pipeline.

Next () method is used to pass the execution to the next middleware.

Map () method is used to map the middleware to a specific URL.

App.Map(“/testmap”, MapCustomMiddleware);

With this when the request comes, if it contains /testmap as part of the URL, then only this
Middleware component going to be executed else simply is ignored.
How to enable routing

 In Asp.Net Core Web application, we can enable routing through middleware


 We need to insert following two middleware in the http pipeline
UseRouting()
UseEndpoint()
Token Replacement

We can replace the value of controller and action method dynamically.

[controller]/[action]

[ApiController]

[Route(“[controller]/[action]”)]

Public class EmployeeController:ControllerBase

[(“Id”)]

Public async Task<List<Employee>> GetAllEmployees()

Return await _employeeDBContext.Employees.ToList();

Return Type

 Specific Type: - use to return specific type example (Employee Type)


 IActionResult
 IActionResult is an interface. It is use to return multiple type of data.
 IActionResult<T>: - return any or specific type of data.
 HttpResponseMessage : HttpResponseMessage including the status code and data.

Model Binder

Bind the incoming HTTP request data to the action method parameter.

[BindProperty]: -

BindProperty is an attribute and it is used to bind the incoming form-data to the public properties of
controller.

BindProperty is applied on each target property individually.


[BindProperty]

Public string Name {get; set ;}

If you want to enable the property with GET method then [BindProperty (supportget=true)].

[BindProperties]:-

BindProperties is applied on the controller level.

Dependency Injection (DI)

 Create an application which is loosely coupled.


 The main concept behind dependency injection (DI) is to implement IOC (Inversion of Control).
 IOC means to have loosely coupling in the code.
 Unit Testing.

How to configure the DI

 Asp.net Core framework provides the built-in support for DI.


 Dependency are registered in containers, and the container in the ASP.NET core is
IServiceCollection.
 Services are registered in the Startup.ConfigureServices method of the application.

Lifetime of Services in DI

 Singleton
 Scoped
 Transient

Singleton

 Singleton services can be registered using AddSingleton<> method.


 There will be only instance of the singleton service throughout the application.
 Services. AddSingleton<IProductRepository,ProductRepository>();

Scoped

 Scoped services can be registered using AddScoped<> method.


 A new instance of the service will be created for new HTTP request.

Transient

 Transient services can be registered using AddTransient<> method.


 A new instance will be created every-time it is requested.

TryAddScoped, TryAddSingleton, TryAddTransient


If you are registering the dependency using AddScoped, AddSingleton or AddTransient method then
they will replace the service in the collection if it has already been registered in the container.

Now if you use the Try version like TryAddScoped then it will only register the service if it was not
registered earlier. In case service was already registered then the TryAddScoped will skip the registration
for that service.

Services.TryAddTransient<IProductRepository, TestRepository>();

Services.TryAddTransient<IProductRepository, ProductRepository>(); - this service will not register as it


was already registered.

Identity Core

Identity core is an open-source framework supported by Microsoft.

Identity core has everything that is required to work with authentication and authorization.

 Signup, Login, change password, Forgot password.


 Multifactor authentication.
 Login with third party app like Google, Facebook, and Microsoft etc.

Add Identity core package:

dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore --version 6.0.3

If you want to add extra properties then create a new class ex (ApplicationUser) inherit
it from IdentityDbContext<ApplicationUser>

Register the service under ConfigureServices method under startup.cs

services.AddIdentity<ApplicationUser,IdentityRole>()
                    .AddEntityFrameworkStores<BookStoreDBContext>()
                    .AddDefaultTokenProviders();

JWT
Install Microsoft.AspNetCore.Authentication.JwtBearer

Add settings under appsettin.json

"JWT":{
    "ValidAudience":"User",
     "ValidIssuer":"https://localhost:5001

",
     "Secret":"BookStore@1234"
  }

Add below coded under configure method

 services.AddAuthentication(option=>{
               
option.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
               
option.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
                option.DefaultScheme=JwtBearerDefaults.AuthenticationScheme;

            })
            .AddJwtBearer(option=>{
                option.SaveToken=true;
                option.RequireHttpsMetadata=false;
                option.TokenValidationParameters=new
Microsoft.IdentityModel.Tokens.TokenValidationParameters(){
                    ValidateIssuer=true,
                    ValidateAudience=true,
                    ValidAudience=Configuration["JWT:ValidAudience"],
                    ValidIssuer=Configuration["JWT:ValidIssuer"],
                    IssuerSigningKey= new
SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["JWT:Secret
"]))
                };
            });  
InProcess and OutProcess

InProcess: is the default hosting model. This means requests forwarded to IIS HTTP server.

OutProcess: it uses kestrel web server (dotnet.exe). It is using two web servers (IIS, Nginx, and
Apache).

What is Host in ASP.NET CORE?

The host configures a server like kestrel or IIS and a request processing pipeline.

How to handle exception in .NET Core Web API?

App. UseExceptionHandler(“/error”).
App. UseDeveloperExceptionPage();

Interface IEmployeeRepository
{
Task<EmployeeResult> GetAllEmployees();
}

Class Employee : IEmployeeRepository


{

Public async Task<EmployeeResult> GetAllEmployees()


{
Var result = await _context. GetAllEmployees();
}
Return result;
}

Implement caching in .NET core


In-Memory Cache:
Step 1: Install below library
Install Microsoft.Extension.Caching.Memory
Step 2: Inject ICacheProvider in controller class

Public class EmployeeController: ControllerBase {


Private ICacheProvider _cacheProvider;
Public EmployeeController(ICacheProvider cacheProvider) {
_cacheProvider = cacheProvider;
}
}

Step 3:

Register services.AddMemoryCache() to ConfigureServices() method in the Startup class. 

public void ConfigureServices(IServiceCollection services)


{
services.AddMemoryCache();
}
[Route("getAllEmployee")]

public IActionResult GetAllEmployee() {

if (!_cache.TryGetValue(CacheKeys.Employees, out List < Employee > employees)) {

employees = GetEmployeesDeatilsFromDB(); // Get the data from database


var cacheEntryOptions = new MemoryCacheEntryOptions {

AbsoluteExpiration = DateTime.Now.AddMinutes(5),

SlidingExpiration = TimeSpan.FromMinutes(2),

Size = 1024,

};

_cache.Set(CacheKeys.Employees, employees, cacheEntryOptions);

return Ok(employees);

In-Memory Cache Parameters


 Size - This allows you to set the size of this particular cache entry, so that it
doesn’t start consuming the server resources.
 SlidingExpiration - How long the cache will be inactive. A cache entry will
expire if it is not used by anyone for this particular time period. In our case, we
have set SlidingExpiration is 2 minutes. If no requests for this cache entry for 2
minutes, then the cache will be deleted.
 AbsoluteExpiration - Actual expiration time for cached value. Once the time is
reached, then the cache entry will be removed. In our case, we have set
AbsoluteExpiration is 5 minutes. The cache will be expired once the time is
reached 5 minutes. Absolute expiration should not less than the Sliding
Expiration.

What is MediaTypeFormatter
MediaTypeFormatter is an abstract class from
which JsonMediaTypeFormatter and XmlMediaTypeFormatter classes inherit from.
JsonMediaTypeFormatter handles JSON and XmlMediaTypeFormatter handles XML.

How to return only JSON from ASP.NET Web API Service irrespective of the Accept
header value
config.Formatters.JsonFormatter.SupportedMediaTypes
    .Add(new MediaTypeHeaderValue("text/html"));

You might also like