0% found this document useful (0 votes)
60 views6 pages

Net Core Notes

Uploaded by

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

Net Core Notes

Uploaded by

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

1.

exceution starts from main method

2. createdefaultbuilder

3. app.useStaticFiles(), app.useDefaultFiles(), app.useFileServer()

4. app.UseDeveloperExceptionPage()

5. ASPNETCORE_ENVIRONMENT (launch settings)

6. IHostingEnvironment access runtime environment

7. addMvc(), addMvcCore- configureservices , addMvcWithDefaultRoute() -


configure

8. ViewData (Dictionary), ViewBag (Dynamic), StronglyTypedView (data from


controller -> view)

9. _Layout.cshtml, RenderSection, RenderBody, _viewStart.cshtml , _viewImports, Tag


Helpers (server side rendering)

10. Conventional [Route("api/v{version:apiVersion}/[controller]")] and Attribute


Routing

11. Tag Helpers

12. subResourceIntegrity -> browser to check if file maliciously altered

13. AddSingleton (single instance - cached ),

Add Scoped (new instance - different http requests)ex: services , repository

Add Transient (new instance - on request of new instance even in same http
scope or different),ex: OAuthHandler

14. DbContext and DbContextOptions, DbSet (tables),

15. configure EF -> configureServices ->


services.AddDbContextPool<AddDbContext>(options=>options.useSqlServer(connectionstr
ing))

16. IOptions in .NET core is used to provide strongly type classes to access
appsettings from the application or vault settings defined in the cloud. It
provides encapsulation for that settings to be dependent on configured class and
separated from other settings.

17. EF Core Migrations is to sync between the database schema and application
models

18. Add-migration , update-database

19. Exception handler in .net core

a. app.UseExceptionHandler("/error"); -> add exception handler middleware


b. Configure a controller action to respond to the /error route:
[Route("/error")]
public IActionResult HandleError() => Problem();
20. Logging in .net Core

1.Create a new Asp.net core web application and add the following custom
error model:
2.Add a DbLoggerOptions class to store the logger settings:
3.Creating the custom logging provider (ILoggerProvider) - Creates a new
instance of the db logger in the CreateLogger function

public ILogger CreateLogger(string categoryName)


{
return new DbLogger(this);
}

4. Add the logger instance and override the Log Method

public class DbLogger : ILogger


{
private readonly DbLoggerProvider
_dbLoggerProvider;

public DbLogger([NotNull] DbLoggerProvider


dbLoggerProvider)
{

_dbLoggerProvider = dbLoggerProvider;
}

5. Then, configuration extension method:

//DbLoggerExtensions.cs
public static class DbLoggerExtensions
{
public static ILoggingBuilder AddDbLogger(this
ILoggingBuilder builder, Action<DbLoggerOptions> configure)
{
builder.Services.AddSingleton<ILoggerProvider,
DbLoggerProvider>();
builder.Services.Configure(configure);
return builder;
}
}

6. Adding the logger provider to the ASP.NET Core application

// Program.cs
var builder = WebApplication.CreateBuilder(args);
...
builder.Logging.AddDbLogger(options =>
{

builder.Configuration.GetSection("Logging").GetSection("Database").GetSection("Opti
ons").Bind(options);
});

var app = builder.Build();


...
app.Run();
21. Authentication (Auth0)

1. At UI we directly call the nucor.auth0.com for credentials validations by


using Auth0 AuthServices

this.auth.loginWithRedirect({
...(this.organization ? { organization:
this.organization } : null),
redirect_uri:
process.CSIRedirectURI+this.csi_uri+?userInfo=${encryptedEmail}
});
by using .... import { AuthService } from
'@auth0/auth0-angular';
2. if user valid then in subsequent calls we send the JWT token in headers
3. At API we validate it with AddAUthentication middleware

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = domain;
options.Audience = audience;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = domain,
ValidateAudience = true,
ValidAudience = audience,
NameClaimType = ClaimTypes.NameIdentifier
};
});

4. on every action method we use the Authorize Attribute for validation

22. Custom MiddleWare

1. create a class and use RequestDelegate and in InvokeAsync Method call next
method

public class CustomMiddleware


{
private readonly RequestDelegate _next;

public CustomMiddleware(RequestDelegate next)


{
_next = next;
}

public async Task InvokeAsync(HttpContext context)


{
// Your custom logic here
await context.Response.WriteAsync("Custom Middleware
Executing...\n");

// Call the next delegate/middleware in the pipeline


await _next(context);
}
}

2. register it by calling app.useMiddleware<CustomMiddleware>()

23. Caching in .NET Core

Caching in .NET Core can significantly improve the performance of your application
by reducing the
need to generate the same data repeatedly. .NET Core supports several types of
caching:

1. In-Memory Caching: Stores cache data in the memory of the web server.
(single Server Scenario's) -> Nucor
2. Distributed Caching: Stores cache data across multiple servers or
services. (multiple server Scenario's) -> IOWA
3. Response Caching: Caches responses for HTTP requests.

1.In-Memory Caching:
a. In startup.cs , add in memory caching services --->
services.AddMemoryCache();
b. Inject IMemoryCache into your controller or service and use it to
set and get cache entries:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

public class HomeController : Controller


{
private readonly IMemoryCache _cache;

public HomeController(IMemoryCache cache)


{
_cache = cache;
}

public IActionResult Index()


{
string cacheKey = "currentTime";
if (!_cache.TryGetValue(cacheKey, out string
currentTime))
{
currentTime = DateTime.Now.ToString();
var cacheEntryOptions = new
MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.From
Seconds(30));

_cache.Set(cacheKey, currentTime,
cacheEntryOptions);
}

ViewBag.CurrentTime = currentTime;
return View();
}
}
24. Authorization

Authorization in .NET Core is a process that determines what an authenticated user


is allowed to do.
It is typically implemented using policies, roles, and claims. Here’s an overview
of how you can set up authorization in a .NET Core application:

a.Role-Based Authorization: Protects resources based on user roles.


b.Policy-Based Authorization: Defines and checks policies based on roles and
claims.
c.Claims-Based Authorization: Uses claims to authorize users for specific
actions.

Step 1
// Add authorization services
services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
options.AddPolicy("CanEditContent", policy =>
policy.RequireClaim("EditContent"));
});

step 2

app.UseAuthorization();

a. Role-Based Authorization
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{

b. Policy-Based Authorization
[Authorize(Policy = "CanEditContent")]
public class ContentController : Controller
{

c. Claims-Based Authorization
You can add claims to a user and use them for authorization. Here’s an example of
how to set a claim:

public class AccountController : Controller


{
public async Task<IActionResult> Login(string returnUrl = null)
{
// Assuming user authentication is successful
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "[email protected]"),
new Claim("EditContent", "true")
};

var claimsIdentity = new ClaimsIdentity(claims,


CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
RedirectUri = returnUrl ?? Url.Content("~/")
};

await
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new
ClaimsPrincipal(claimsIdentity), authProperties);

return LocalRedirect(returnUrl ?? "/");


}
}

25. ConfigureServices: Registers services and configures the DI container.


Configure: Defines the middleware pipeline and how the application responds to HTTP
requests.

You might also like