ASP.NET Core


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)

    N

    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 put cache-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 the MapControllers() while after the UseCors()): in this case, server will also do the cache for actions according to their [ResponseCache] setting

  • If 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

    1. appsettings.json under project directory
    2. existing IConfiguration
    3. appsettings.{Environment}.json under project directory
    4. environmental variables
    5. CMD Line
    6. 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 or app.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 interface IWebHostEnvironment, you can use it in any controllers like this

ASP.NET Config Security

  • How to protect secret config information

    1. write secrets into a json file, but don’t put that file into our project
    2. write click ASP.NET project, choose Manage User Secrets
    3. write your secrets there
    4. 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 use

  • How to pool the DbContext

    But it is not recommended beacause

    1. DbContextPool is a singleton service, and singleton service and can not use scoped and transient services
    2. 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:

    1. you should have entityframeworkcore package

    2. create IdentityUser, IdentityRole and IdentityDbContext key is the type of main index

      image-20230912162329207

    3. set auth rule in Program.cs

    4. Using EF(migration, update) to update relevant auth tables in DB

    5. 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 function

  • Generate token

  • Validate Token:

  • Use JWT in ASP.NET

    1. install Microsoft.AspNetCore.Authentication.JwtBearer

    2. config in Program.cs

    3. add app.UseAuthentication() before the app.UseAuthorization()

    4. 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

    5. Create a jwt send, receive mechanism. Only allow a specific role to access a specific method

      sender:

      4

      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

    1. Add jwt version column to user entity

    2. update the jwt version and put it into the payload when user successfully login

    3. 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

      image-20231006170659754

    • 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:

    1. Create custom hub class

    2. Register the services and path in Program.cs(path should above MapControllers)

    3. Open CORS


A u t h o r: Joe
P o l i c y: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source Joe !
Leave Your Comment Here
  TOC