.NET Core #dotnet
The .NET Core platform is a new .NET stack that is optimized for open source development and agile delivery on NuGet.
Advantages:
Cross platform framework-Windows, Linux and mac OS for building modern web apps and web APIs
Open Source-Free to use
Integration of Modern UI Framework-Angular, React
Hosting-Kestrel, IIS and nginx
Build in Dependency Injection -Loosely coupled, Reusability
Architected for testability
Razor Pages for easier coding of page-focused scenarios
Unparalleled performance, scalability, and versatility
?
Disadvantages
?
Configure Services Method:
·?????? Configuring services in .NET Core involves setting up dependency injection and configuring various services your application will use.?
·?????? ?The?Program.cs?file is where you configure services and the app pipeline.
·?????? It is optional
·?????? Add services to the container: Use the?builder.Services?property to add services.?
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddTransient<IMyService, MyService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();
configuration settings:
·?????? You can access configuration settings from various sources like?appsettings.json, environment variables, etc.?
var builder = WebApplication.CreateBuilder(args);
// Load configuration from appsettings.json
builder.Configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var app = builder.Build();
Configure Methods:
·?????? The?Configure?method is used to define how the application will respond to HTTP requests. This method sets up the middleware components that handle requests and responses.
public class Startup
{
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Key Differences
?
Dependency Injection
·?????? Helps to create loosely coupled design of the application.
o?? Register Services
·?????? Addresses several key problems in ASP.NET Core, leading to a more robust and maintainable application:
o?? Tight Coupling.
o?? Code Rigidity.
o?? Testing Difficulties.
o?? Maintainability Challenges.
?
Service Lifetimes:
Inject Services:
·?????? You can inject services into your controllers or other classes via constructor injection.
public class MyController : ControllerBase
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
[HttpGet]
public IActionResult Get()
{
var result = _myService.DoSomething();
return Ok(result);
}
}
Using DI in Middleware:
·?????? You can also inject services into middleware components.
public class MyMiddleware
{
private readonly RequestDelegate _next;
private readonly IMyService _myService;
public MyMiddleware(RequestDelegate next, IMyService myService)
{
_next = next;
_myService = myService;
}
public async Task InvokeAsync(HttpContext context)
{
_myService.DoSomething();
await _next(context);
}
}
Configuration and Options Pattern:
·?????? You can use the options pattern to manage configuration settings.
public class MyOptions
{
public string Option1 { get; set; }
public int Option2 { get; set; }
}
// Register options
builder.Services.Configure<MyOptions>(builder.Configuration.GetSection("MyOptions"));
// Inject options
public class MyService
{
private readonly MyOptions _options;
public MyService(IOptions<MyOptions> options)
{
_options = options.Value;
}
}
Kestrel:
·?????? Kestrel is?a cross-platform web server for ASP.NET Core. Kestrel is the recommended server for ASP.NET Core, and it's configured by default in ASP.NET Core project templates.
?
Key Features of Kestrel
Configuring Kestrel
·?????? You can configure Kestrel in the?Program.cs?file or in the?appsettings.json?file.
var builder = WebApplication.CreateBuilder(args);
// Configure Kestrel server options
builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
serverOptions.Listen(IPAddress.Any, 5000); // Listen on port 5000
});
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
Use Kestrel
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
Architecture:
·?????? The architecture of .NET Core is designed to be modular, lightweight, and cross-platform, making it suitable for building modern, high-performance applications
·?????? Built on .NET Core runtime
Key Components
Architectural Concepts
?
Reading appsetting values
public class MyController : Controller
{
private readonly IConfiguration _configuration;
public MyController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
string connectionString = _configuration.GetValue<string>("ConnectionStrings:Default");
// Use the connection string to access your database...
return View();
}
}
Middleware
?Middleware in ASP.NET Core is a crucial concept that involves a series of components used to handle requests and responses in an application. Each middleware component in the pipeline can perform operations before and after the next component in the pipeline. Here are some key points about middleware in ASP.NET Core:
1. Request Pipeline: Middleware components are assembled into an app pipeline to handle requests and responses. Each component decides whether to pass the request to the next component or to handle it directly1.
2. Built-in Middleware: ASP.NET Core provides a rich set of built-in middleware components, such as authentication, authorization, logging, and more1.
3. Custom Middleware: You can also create custom middleware to handle specific tasks. Custom middleware is typically encapsulated in a class and exposed with an extension method2.
4. Order of Middleware: The order in which middleware components are added to the pipeline is crucial, as it determines the sequence of request processing1.
5. Short-circuiting: Middleware can short-circuit the pipeline, meaning it can prevent further middleware from processing the request if certain conditions are met.
using System.Globalization;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseHttpsRedirection();
app.Use(async (context, next) => {
var cultureQuery = context.Request.Query["culture"];
if (!string.IsNullOrWhiteSpace(cultureQuery)) {
var culture = new CultureInfo(cultureQuery);
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;
}
await next(context);
});
app.Run(async (context) => {
await context.Response.WriteAsync($"CurrentCulture.DisplayName: {CultureInfo.CurrentCulture.DisplayName}");
});
app.Run();
?App.Run:
In .NET Core, the app.Run method is used to define a terminal middleware delegate in the application’s request pipeline. This means it handles the request and generates a response directly, without passing the request to any subsequent middleware components.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, World!");
});
app.Run();
In this example, the app.Run method is used to respond with “Hello, World!” to any incoming HTTP request. Once app.Run is called, it terminates the pipeline, meaning no further middleware will be executed
App.Use:
In .NET Core, the app.Use method is used to add middleware components to the application’s request pipeline. Middleware are software components that are assembled into an application pipeline to handle requests and responses. Each component chooses whether to pass the request to the next component in the pipeline.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next) =>
{
// Do something before the next middleware
await context.Response.WriteAsync("Before next middleware\n");
await next.Invoke(); // Call the next middleware
// Do something after the next middleware
await context.Response.WriteAsync("After next middleware\n");
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from the terminal middleware!\n");
});
app.Run();