asp.net core uses DI to implement a customized user system
Preface
In many cases we don’t actually need the complex user system that asp.net core comes with, based on roles, various concepts, and You have to use EF Core, and in web applications, information is stored in cookie for communication (I don’t like to put it in cookies, because once I ran the web application in the safari browser on the mac system , when cross-domain cookies cannot be set, I have to use a very special method, remember it is iframe, which is quite troublesome, so I still like to put it in the custom header ), I feel kidnapped by Microsoft after using it. However, this is completely a personal preference. You can do whatever you like. I have provided another way here so that you can have one more choice.
I use asp.net core's Dependency Injection to define a set of user authentication and authorization for my own system. You can refer to this to define your own. Limited to user system.
Aspect-orientedProgramming(AOP)
In my opinion, Middleware and Filter are both aspects in asp.net core. We can put authentication and authorization in these two places. I personally prefer to put the authentication in Middleware, which can intercept and return illegal attacks early.
Dependency Injection (DI)
There are three types of dependency injectionLife cycle
1. From the initiation to the end of the same request. (services.AddScoped)
2. Each time it is injected, it is newly created. (services.AddTransient)
3. Singleton, from the beginning of the application to the end of the application. (services.AddSingleton)
My custom user class uses services.AddScoped.
Specific methods
1. Define user class
1 // 用户类,随便写的2 public class MyUser3 {4 public string Token { get; set; }5 public string UserName { get; set; }6 }
2. Register user class
in Startup.cs The ConfigureServices function:
1 // This method gets called by the runtime. Use this method to add services to the container.2 public void ConfigureServices(IServiceCollection services)3 {4 ...5 // 注册自定义用户类6 services.AddScoped(typeof(MyUser));7 ...8 }
custom user class is registered through services.AddScoped because I want it to be in the same request , Middleware, filter, controllerreference refers to the same object.
3. Inject into Middleware
1 // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project 2 public class AuthenticationMiddleware 3 { 4 private readonly RequestDelegate _next; 5 private IOptions<HeaderConfig> _optionsAccessor; 6 7 public AuthenticationMiddleware(RequestDelegate next, IOptions<HeaderConfig> optionsAccessor) 8 { 9 _next = next;10 _optionsAccessor = optionsAccessor;11 }12 13 public async Task Invoke(HttpContext httpContext, MyUser user)14 {15 var token = httpContext.Request.Headers[_optionsAccessor.Value.AuthHeader].FirstOrDefault();16 if (!IsValidate(token))17 {18 httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;19 httpContext.Response.ContentType = "text/plain";20 await httpContext.Response.WriteAsync("UnAuthentication");21 }22 else23 {24 // 设置用户的token25 user.Token = token;26 await _next(httpContext);27 }28 }29 30 // 随便写的,大家可以加入些加密,解密的来判断合法性,大家自由发挥31 private bool IsValidate(string token)32 {33 return !string.IsNullOrEmpty(token);34 }35 }36 37 // Extension method used to add the middleware to the HTTP request pipeline.38 public static class AuthenticationMiddlewareExtensions39 {40 public static IApplicationBuilder UseAuthenticationMiddleware(this IApplicationBuilder builder)41 {42 return builder.UseMiddleware<AuthenticationMiddleware>();43 }44 }
I found that if I want to inject the interface/class into Middleware in Scoped mode, just The class/interface to be injected needs to be placed in the parameters of the Invoke function, not the constructor# of Middleware ##, I guess this is why Middleware does not inherit the base class or interface, and defines Invoke in the base class or interface. If it defines Invoke in the base class or interface, this Invoke will inevitably The parameters must be fixed, so dependency injection is difficult.
4. Only by configuring certain paths will the Middleware be used.1 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 2 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 3 { 4 loggerFactory.AddConsole(Configuration.GetSection("Logging")); 5 loggerFactory.AddDebug(); 6 // Set up nlog 7 loggerFactory.AddNLog(); 8 app.AddNLogWeb(); 9 10 // 除了特殊路径外,都需要加上认证的Middleware11 app.MapWhen(context => !context.Request.Path.StartsWithSegments("/api/token")12 && !context.Request.Path.StartsWithSegments("/swagger"), x =>13 {14 // 使用自定义的Middleware15 x.UseAuthenticationMiddleware();16 // 使用通用的Middleware17 ConfigCommonMiddleware(x);18 });19 // 使用通用的Middleware20 ConfigCommonMiddleware(app);21 22 // Enable middleware to serve generated Swagger as a JSON endpoint.23 app.UseSwagger();24 25 // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.26 app.UseSwaggerUI(c =>27 {28 c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");29 });30 }31 32 // 配置通用的Middleware33 private void ConfigCommonMiddleware(IApplicationBuilder app)34 {35 // cors36 app.UseCors("AllowAll");37 38 app.UseExceptionMiddleware();39 // app.UseLogRequestMiddleware();40 app.UseMvc();41 }
1 public class NeedAuthAttribute : ActionFilterAttribute 2 { 3 private string _name = string.Empty; 4 private MyUser _user; 5 6 public NeedAuthAttribute(MyUser user, string name = "") 7 { 8 _name = name; 9 _user = user;10 }11 12 public override void OnActionExecuting(ActionExecutingContext context)13 {14 this._user.UserName = "aaa";15 }16 }
1 [TypeFilter(typeof(NeedAuthAttribute), Arguments = new object[]{ "bbb" }, Order = 1)]2 public class ValuesController : Controller
1 public class ValuesController : Controller 2 { 3 private MyUser _user; 4 5 public ValuesController(MyUser user) 6 { 7 _user = user; 8 } 9 ...10 }
The above is the detailed content of asp.net core uses DI to implement a customized user system. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.
