HTTTP/Middleware/MVC Flashcards
Kestrel
Kestrel is a cross-platform web server for ASP.NET Core, a web framework for building modern, cloud-based, and internet-connected applications. It is the default web server included with ASP.NET Core projects and is designed to be lightweight, high-performance, and scalable.
Reverse proxy servers- examples
IIS
Nginx
Apache
Reverse proxy to serwer, który przyjmuje żądania HTTP od klientów (np. przeglądarek) i przekazuje je do jednego lub więcej serwerów aplikacji w celu przetworzenia. Odpowiedzi z serwera aplikacji są następnie wysyłane z powrotem do klienta przez serwer proxy. W przeciwieństwie do forward proxy, który działa w imieniu klienta, reverse proxy działa w imieniu serwera.
Benefits of Reverse Proxy Servers
Load Balancing
Caching
URL Rewriting
Decompressing the requests
Authentication
Decryption of SSL Certificates
IIS express benefits
HTTP access logs
Port sharing
Windows authentication
Management console
Process activation
Configuration API
Request filters
HTTP redirect rules
HTTP
is an application-protocol that defines set of rules to send request from browser to server and send response from server to browser.
HTTP Response Status Codes
1xx | Informational
101 Switching Protocols
2xx | Success
200 OK
3xx | Redirection
302 Found
304 Not Modified
4xx | Client error
400 Bad Request
401 Unauthorized
404 Not Found
5xx | Server error
500 Internal Server Error
Response Start Line
Includes HTTP version, status code and status description.
HTTP Version: 1/1 | 2 | 3
Status Code: 101 | 200 | 302 | 400 | 401 | 404 | 500
Status Description: Switching Protocols | OK | Found | Bad Request | Unauthorized | Not Found | Internal Server Error
HTTP Response Headers
Date
Date and time of the response. Ex: Tue, 15 Nov 1994 08:12:31 GMT
Server
Name of the server.
Ex: Server=Kestrel
Content-Type
MIME type of response body.
Ex: text/plain, text/html, application/json, application/xml etc.
Content-Length
Length (bytes) of response body.
Ex: 100
Cache-Control
Indicates number of seconds that the response can be cached at the browser.
Ex: max-age=60
Set-Cookie
Contains cookies to send to browser.
Ex: x=10
HTTP Request Methods
GET
Requests to retrieve information (page, entity object or a static file).
Post
Sends an entity object to server; generally, it will be inserted into the database.
Put
Sends an entity object to server; generally updates all properties (full-update) it in the database.
Patch
Sends an entity object to server; generally updates few properties (partial-update) it in the database.
Delete
Requests to delete an entity in the database.
GET request
Used to retrieve data from server.
Parameters will be in the request url (as query string only).
Can send limited number of characters only to server. Max: 2048 characters
Used mostly as a default method of request for retrieving page, static files etc.
Can be cached by browsers / search engines.
POST request
Used to insert data into server
Parameters will be in the request body (as query string, json, xml or form-data).
Can send unlimited data to server.
Mostly used for form submission / XHR calls
Can’t be cached by browsers / search engines.
Middleware
Middleware is a component that is assembled into the application pipeline to handle requests and responses.
Middlewares are chained one-after-other and execute in the same sequence how they’re added.
Middleware can be a request delegate (anonymous method or lambda expression) [or] a class.
Http Context + Next
Middleware - Run
app.Run( )
The extension method called “Run” is used to execute a terminating / short-circuiting middleware that doesn’t forward the request to the next middleware.
app.Use( )
The extension method called “Use” is used to execute a non-terminating / short-circuiting middleware that may / may not forward the request to the next middleware.
Middleware Class
class MiddlewareClassName : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
//before logic
await next(context);
//after logic
}
}
app.UseMiddleware<MiddlewareClassName>();</MiddlewareClassName>
Middleware extension method is used to invoke the middleware with a single method call.
Middleware chain
app.UseExceptionHandler(“/Error”);
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.MapControllers();
//add your custom middlewares
app.Run();
Middleware - UseWhen
app.UseWhen(
context => { return boolean; },
app =>
{
//add your middlewares
}
);
The extension method called “UseWhen” is used to execute a branch of middleware only when the specified condition is true.
Routing
Routing is a process of matching incoming HTTP requests by checking the HTTP method and url; and then invoking corresponding endpoints.
Default Route Parameters
“{parameter=default_value}”
A route parameter with default value matches with any value.
It also matches with empty value. In this case, the default value will be considered into the parameter.
Optional Route Parameters
“{parameter?}”
”?” indicates an optional parameter.
That means, it matches with a value or empty value also.
Custom Route Constraint Classes
public class ClassName : IRouteConstraint
{
public bool Match(HttpContext? HttpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
//return true or false
}
}
Endpoint Selection Order
1: URL template with more segments.
Eg: “a/b/c/d” is higher than “a/b/c”.
2: URL template with literal text has more precedence than a parameter segment.
Eg: “a/b” is higher than “a/{parameter}”.
3: URL template that has a parameter segment with constraints has more precedence than a parameter segment without constraints.
Eg: “a/b:int” is higher than “a/b”.
4: Catch-all parameters ().
Eg: “a/{b}” is higher than “a/”.
Controller
Controller is a class that is used to group-up a set of actions (or action methods ).
Action methods do perform certain operation when a request is received & returns the result (response).
Controllers should be either or both:
The class name should be suffixed with “Controller”. Eg: HomeController
The [Controller] attribute is applied to the same class or to its base class.
Controller
[Controller]
class ClassNameController
{
//action methods here
}
Optional:
Is a public class.
Inherited from Microsoft.AspNetCore.Mvc.Controller.
Responsibilities of Controllers
Reading requests
Extracting data values from request such as query string parameters, request body, request cookies, request headers etc.
Invoking models
Calling business logic methods.
Generally business operations are available as ‘services’.
Validation
Validate incoming request details (query string parameters, request body, request cookies, request headers etc.)
Preparing Response
Choosing what kind of response has to be sent to the client & also preparing the response (action result ).
IActionResult
It is the parent interface for all action result classes such as ContentResult, JsonResult, RedirectResult, StatusCodeResult, ViewResult etc.
By mentioning the return type as IActionResult, you can return either of the subtypes of IActionResult
Model Binding
Model Binding is a feature of asp.net core that reads values from http requests and pass them as arguments to the action method.
Models
Model is a class that represents structure of data (as properties) that you would like to receive from the request and/or send to the response.
Also known as POCO (Plain Old CLR Objects).
Model Validation
class ClassName
{
[Attribute] //applies validation rule on this property
public type PropertyName { get; set; }
}
IsValid
Specifies whether there is at least one validation error or not (true or false).
Values
Contains each model property value with corresponding “Errors” property that contains list of validation errors of that model property.
ErrorCount
Returns number of errors.
Model Validation examples
[Required(ErrorMessage = “value”)]
Specifies that the property value is required (can’t be blank or empty).
[StringLength(int maximumLength, MinimumLength = value, ErrorMessage = “value”)]
Specifies minimum and maximum length (number of characters) allowed in the string.
[Range(int minimum, int maximum, ErrorMessage = “value”)]
Specifies minimum and maximum numerical value allowed.
[RegularExpression(string pattern, ErrorMessage = “value”)]
Specifies the valid pattern (regular expression).
[EmailAddress(ErrorMessage = “value”)]
Specifies that the value should be a valid email address.
[Phone(ErrorMessage = “value”)]
Specifies that the value should be a valid phone number).
Eg: (999)-999-9999 or 9876543210
[Compare(string otherProperty, ErrorMessage = “value”)]
Specifies that the values of current property and other property should be same.
[Url(ErrorMessage = “value”)]
Specifies that the value should be a valid url (website address).
Eg: http://www.example.com
[ValidateNever]
Specifies that the property should not be validated (excludes the property from model validation).
Custom Validations
class ClassName : ValidationAttribute
{
public override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
//return ValidationResult.Success;
//[or] return new ValidationResult(“error message”);
}
}
IValidatableObject
Base class for model classes with validation.
Provides a method called Validate() to define class level validation logic.
The Validate() method executes after validating all property-level validations are executed; but doesn’t execute if at least one property-level validations result error.