Action Parameters Source
Normally, the ASP.NET will speculate the source(body or query string or URL) of your action parameters. But you can also explicitly indicate that.
Explicit parameters in URL
what if parameter name in URL should be different with that in method
Explicit from query string(all parameters are default from query string)
Explicit from request body
Explicit from header
DI in ASP.NET
In asp.net, you can use method injection to only injection the instance when a specific method is invoked instead for a controller. So that some heavy injected instance will not affect other actions in a controller
Header Cache in ASP.NET
By only using
ResponseCache
attribute to an action, ASP.NET will automatically putcache-control:max-age
to the response header, indicating the browser could cache the result the the response(client side cache)use server side cache(
UseResponseCaching()
should be prior to theMapControllers()
while after theUseCors()
): in this case, server will also do the cache for actions according to their [ResponseCache] settingIf the browser’s cache is banned, even if there is a server side cache, the server will not use the cache
Memory Cache in ASP.NET
basic use
expire strategy
Absolute expiration
Sliding expiration(one more new request will reset the expiration time )
Use 2 types both: The expiration time of it keeps extending by one window length as long as it is accessed within the window period, but it cannot exceed the absolute expiration time point.
Cache Penetration: cache penetration means, when there is a query for a non-existing data, the cache will pass this query to the database and if someone maliciously send a lot of these kind of request, the db server will receive a lot of query even if we set the cache for the system
solution: use GetOrCreateAsync, because it will take the null as a value as well, so it will not pass query to the database further when it receives another request
Cache Breakdown: too much cache expire in the same time range, causing the cache does not work for that period of time.
Solution: add a random expiration time to the base expiration time for each cache item
ASP.NET and Env
ASP.NET will default load
- appsettings.json under project directory
- existing IConfiguration
- appsettings.{Environment}.json under project directory
- environmental variables
- CMD Line
- user secrets
in to its app.Configuration, so no need to manually load them into app’s config root
ASP.NET will automatically read a variable named ASPNETCORE_ENVIRONMENT in the environment, 3 environments: Development, Staging, Production(default) are recommended
you can get the value by
app.EnvironmentName
orapp.IsDeveloment()
app.IsStaging()
,app.IsProduction()
In ASP.NET, read other environment variable using
In the developing phase, there is a shortcut in VS for developers to set fake environment variables, instead of really setting an EV
Project Proterty -> debug -> general -> Open debug launch profiles UI -> asp.net -> Environment variables
!! the EV in this setting will override the real system EV’s value
In asp.net, the instance
app.Environment
will be automatically injected using the interfaceIWebHostEnvironment
, you can use it in any controllers like this
ASP.NET Config Security
How to protect secret config information
- write secrets into a json file, but don’t put that file into our project
- write click ASP.NET project, choose
Manage User Secrets
- write your secrets there
- the secret file will be stored under the directory: C:\Users{username}\AppData\Roaming\Microsoft\UserSecrets
How to read secret
Optional Pattern in ASP.NET
In Program.cs
In controllers
EF Core in ASP.NET
In an ASP.NET project, the EF core related file should be put in another project under the same solution
How to use it
In DbContext File, add injected option in constructor
In Program.cs
In controllers
When you run
add migrations
command under a multi project solution, you may fail. To successfully run it, you have to create a class implemented IDesignTeimDbConteaxtFactory, which can build up the connection between your code and db dotnet ef tool to useHow to pool the DbContext
But it is not recommended beacause
- DbContextPool is a singleton service, and singleton service and can not use scoped and transient services
- not so meaningful
ASP.NET Filter
Filter in ASP.NET is a realization of AOP
There are
Authorization Filter
Resource Filter
Exception Filter
Result Filter
Action Filter
In the ASP.NET
ASP.NET will default give you an Exception Filter, and it will only work under the development environment, we can also define our own exception filter
Define an exception filter
In Program.cs, injected the filter
Action filter
Self-defined action filter
In Program.cs
Action Filter Example 1: transaction filter
Open a transaction scope in a controller action for DB operations
What if we don’t want to add this scope to every action that needs transaction, in this case, we can define a global tansaction action filter:
Action Filter Example 2: Rate limit filtet(with memory cache function)
Identity in ASP.NET
Identity framework is a framework that asp.net provides to help you do the authentication and authorization. It uses EF Core to operate on database
use identity framework:
you should have entityframeworkcore package
create IdentityUser
, IdentityRole and IdentityDbContext key is the type of main index set auth rule in Program.cs
Using EF(migration, update) to update relevant auth tables in DB
Use the Identity in controller(in controller, we use userManager and RoleManager to manage the identity table instead of the db context itself, the injection of these 2 instances is carried out by idBuilder in Program.cs)
This example shows a login controller, Identity will automatically locked user after several times
.CheckPasswordAsync(user, pwd)
method failures.You can also manually specify the maximum retry times and lock time span in Program.cs
Reset Password Function:
Send Token(in here, if you want to generate long tokens or tokens in formats you want, you can set it in Program.cs)
Reset Password:
JWT in ASP.NET
You need
System.IdentityModel.Tokens.JWT
to realize jwt functionGenerate token
Validate Token:
Use JWT in ASP.NET
install
Microsoft.AspNetCore.Authentication.JwtBearer
config in
Program.cs
add
app.UseAuthentication()
before theapp.UseAuthorization()
use jwt in controller
send jwt:
receive and analyze jwt, and its payload: put [Authorize] attribute to methods or controllers that require valid jwt to access
Create a jwt send, receive mechanism. Only allow a specific role to access a specific method
sender:
receiver:
Add header in Swagger
builder.Services.AddSwaggerGen(c => { var scheme = new OpenApiSecurityScheme() { Description = "Authorization header. \r\nExample: 'Bearer 12345abcdef'", Reference = new OpenApiReference{Type = ReferenceType.SecurityScheme, Id = "Authorization"}, Scheme = "oauth2",Name = "Authorization", In = ParameterLocation.Header,Type = SecuritySchemeType.ApiKey, }; c.AddSecurityDefinition("Authorization", scheme); var requirement = new OpenApiSecurityRequirement(); requirement[scheme] = new List
(); c.AddSecurityRequirement(requirement); }); JWT withdrawal problem: JWT put the HTTP state in client side, which will make the withdrawal a bit difficult**(imagine withdraw the former jwt when a user logins in another place**), in this case, we can add version to jwt: put a column called jwt version in user table, every time we issue a jwt, we put that version number into the payload of the jwt, if the received jwt version is smaller than that in database, we invalidate that jwt
Add jwt version column to user entity
update the jwt version and put it into the payload when user successfully login
add filter to check jwt version
Host Service in ASP.Net
host services are those services who are not meant to serve user, these services can be counted as host services:
- export data in every day’s 3pm to database
- for every 5 seconds, update 2 tables
How to use it:
Create hosted service class
Register
Attention: from .Net 6, the exception from hosted services will cause the whole program shut down. Can set HostOptions.BackgroundServicesExceptionBehavior as ignore to ignore the exception from hosted services. But it is not recommended, the recommended way is to wrap codes in hosted service in try-catch blocks
The hosted service will be injected as singleton, so you can not use other scoped services inside it, like DbContext. If you must use them, you can create a scope to use it in the hosted service like this:
SIGNALR
How to this it:
Create custom hub class
Register the services and path in Program.cs(path should above MapControllers)
Open CORS