.NET/C# Interview Question Summary Series: ASP.NET Core Topics

1. How to inject service into controller?

Configure this service in the config services method. And in the constructor of the controller, add this dependency injection.

2. Talk about your understanding of DDD?

DDD, Domain Driven Design. It is to guide software design through domains. It is a very abstract software design idea, which is mainly divided into strategic design and tactical design.
In terms of strategy, divide the domain model through event storms, divide the core domain, sub-domains, and support domains, define a common language, and divide the boundary context.
In terms of tactical design, ddd layers the architecture, and "loose coupling, high cohesion" is the overall idea of ​​architecture design. According to the idea of ​​DDD, it can be divided into domain layer, infrastructure layer, application layer, and interface layer.
The interface layer provides API interface for front-end users. The infrastructure layer can contain some third-party services, database connections, etc. The application layer is the orchestration of domain services, which is a very thin layer (currently my own architecture uses cqrs, and all relevant logic is placed in the application layer, while the domain layer just puts Entities, because I don’t really understand what services and events in the domain layer should write for the time being). The domain layer includes entities, value objects, aggregate roots, domain services, domain events, etc.

3. What is the advantage of ASP.NET Core over ASP.NET?

  1. Cross-platform, ASP.NET Core can run on Windows, Linux and MAC systems;
  2. There is no dependency on the framework installation, all dependencies are with the program itself;
  3. ASP.NET Core processes requests more efficiently and can handle more requests;
  4. ASP.NET Core has more installation and configuration methods.

4. What are the main features of asp.net core?

  1. Dependency injection.
  2. Logging system architecture.
  3. Introduces a cross-platform web server, kestrel. It can run alone without iis, apache and nginx.
  4. Apps can be created using the command line.
  5. Use AppSettings.json to configure the project.
  6. Use start up to register the service.
  7. Better support for asynchronous programming.
  8. Support web socket and signal IR.
  9. Prevention and protection mechanism for cross-site requests.

5. How does ASP.NET Core Filter support dependency injection?

  1. Can be registered globally to support dependency injection
  2. Marked in the method by TypeFilter(typeof(Filter)), marked in the controller
  3. By marking the method with ServiceType (typeof(Filter)) and marking it in the controller, you must register the Filter category; the
    essence of TypeFilter and ServiceType is to implement an IFilterFactory interface;

6. What exception handling solutions are there in Asp.Net Core?

1. Inheriting Controller, rewriting OnActionExecuted
will inherit a Controller class by default, rewriting OnActionExecuted, and adding exception handling. Generally, we will create
a new BaseController and let all Controllers inherit from BaseController. code show as below:

  public class BaseController : Controller
    {
    
    
        public override void OnActionExecuted(ActionExecutedContext context)
        {
    
    
            var exception = context.Exception;
            if (exception != null)
            {
    
    
                context.ExceptionHandled = true;
                context.Result = new ContentResult
                {
    
    
                    Content = $"BaseController错误 : {
      
       exception.Message }"
                };
            }
            base.OnActionExecuted(context);
        }
    }

2. Use ActionFilterAttribute.
ActionFilterAttribute is a feature that implements IActionFilter and IResultFilter itself, so whether it is an error thrown in an action or in a view, it can theoretically be caught. We create a new ExceptionActionFilterAttribute, rewrite OnActionExecuted and OnResultExecuted, and add exception handling. The complete code is as follows:

public class ExceptionActionFilterAttribute : ActionFilterAttribute
    {
    
    
        public override void OnActionExecuted(ActionExecutedContext context)
        {
    
    
            var exception = context.Exception;
            if (exception != null)
            {
    
    
                context.ExceptionHandled = true;
                context.Result = new ContentResult
                {
    
    
                    Content = $"错误 : {
      
       exception.Message }"
                };
            }
            base.OnActionExecuted(context);
        }

        public override void OnResultExecuted(ResultExecutedContext context)
        {
    
    
            var exception = context.Exception;
            if (exception != null)
            {
    
    
                context.ExceptionHandled = true;
                context.HttpContext.Response.WriteAsync($"错误 : {
      
      exce  ption.Message}");
            }
            base.OnResultExecuted(context);
        }
    }

There are two ways to use it.
Label the [TypeFilter(typeof(ExceptionActionFilter)] in the controller; inject it globally as a filter in the Startup.

 services.AddControllersWithViews(options =>
 {
    
    
 	options.Filters.Add<ExceptionActionFilterAttribute>();
 })

3. Use IExceptionFilter
We know that Asp.Net Core provides 5 types of filters, and IExceptionFilter is one of them. As the name suggests, it is used to handle exceptions. ExceptionFilterAttribute in Asp.net Core has already implemented IExceptionFilter, so we only need to inherit ExceptionFilterAttribute and rewrite its methods. Also create a new CustomExceptionFilterAttribute to inherit ExceptionFilterAttribute, rewrite OnException, and add exception handling. The complete code is as follows:

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
    
    
        public override void OnException(ExceptionContext context)
        {
    
    
            context.ExceptionHandled = true;
            context.HttpContext.Response.WriteAsync($"CustomExceptionF}");
            base.OnException(context);
        }
    }

4. Use ExceptionHandler.
In the startup, the new project of VS will be added by default.

 if (env.IsDevelopment())
 {
    
    
	 app.UseDeveloperExceptionPage();
 }
else
{
    
    
    app.UseExceptionHandler("/Home/Error");
}

5. Customize Middleare processing
through middleware global processing

public class ErrorHandlingMiddleware
    {
    
    
        private readonly RequestDelegate next;

        public ErrorHandlingMiddleware(RequestDelegate next)
        {
    
    
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
    
    
            try
            {
    
    
                await next(context);
            }
            catch (System.Exception ex)
            {
    
    
                //处理异常
            }
        }
    }

7. Introduce the life cycle of services in ASP.NET Core?

ASP.NET Core supports the Dependency Injection software design pattern, which allows injecting our services in different components and controlling the initialization of the services. Some services can be initialized in a short period of time and can only be used in a particular component and request; and some services can be used in the entire application only after being initialized once .
Singleton -- singleton mode:
Only one instance of the service is created, and this instance is stored in memory and can be used throughout the application. We can use the Singleton mode for some services that are expensive to initialize. In code it can be like this:

 services.AddSingleton<IProductService, ProductService>();

Scoped --
In this mode, an instance of the service will be created for each request. All middleware, MVC controllers, etc. in the same request will get the same service instance. Entity Framework Context is the best reference example of a Scoped service. We can use the Scoped pattern by using the AddScoped method:

 services.AddScoped<IProductService, ProductService>();

Transient -- In short-lived and transient
Transient mode, a service instance is created every time a service is requested. This mode is especially suitable for lightweight, stateless services. We can use the AddTransient method to inject services:

services.AddTransient<IProductService, ProductService>();

8. What is dependency injection?

Dependency injection is a process, that is, when a class needs to call another class to complete a certain task, do not go to the new object of the called class in the calling class, but inject way to get such an object. The specific implementation is to have an interface of the called class in the calling class, and then complete the task by calling the function of the interface. For example, if A calls B, and B implements interface C, then a variable D is defined by C in A. The instance of this variable is not created in A, but obtained through the context of A. The advantage of this is that class A and B are separated, and they are connected by interface C, so as to realize interface programming.

9. What are the ways of dependency injection?

Setter injection:
define a property D of a C interface in class A, instantiate an object through B in the context of A, and then assign this object to property D. The main thing is set and get
constructor injection:
when creating an object of A, the object of B is passed into A through parameters. Another common injection method is the application of the factory mode, which can put the instantiation of B outside of A, so that A and B have no relationship. There is also an interface injection, that is, there is an attribute of the service class (B) in the interface of the client class (A). After instantiating the subclass of this interface, assign a value to this property, which is the same as setter injection.
Compared with constructor
injection and property injection, interface injection is somewhat complicated and not commonly used. The specific idea is to define an interface first, including a method for setting dependencies. Then rely on the class, inherit and implement this interface.

10. What is inversion of control?

Inversion of Control (IoC for short) is a design principle in object-oriented programming that can be used to reduce the coupling between computer codes. The most common way is called dependency injection (Dependency Injection, DI for short), and another way is called "Dependency Lookup".
Through inversion of control, when an object is created, a reference to the object it depends on is passed to it by an external entity that regulates all objects in the system. It can also be said that dependencies are injected into objects.

11. What are the famous frameworks for dependency injection?

Unity、autofac、http://spring.net、MEF、Injection、Asp.Net Core的ServiceCollection。

12. Introduce some ABP.NEXT?

ASP.NET Boilerplate is an excellent open source web application framework for the .Net platform, and has a large number of fans in China. As can be seen from the name, this is the next-generation framework of ASP.NET Boilerplate. The ABP framework was created in 2013. At that time, there was no .Net Core and ASP.NET Core, and there was no Angular2+. After the ABP was released, they were all developed from scratch.
ASP.NET Core introduces many built-in solutions (extension library) for dependency injection, logging, caching, localization, configuration, etc. They are virtually independent of ASP.NET Core and can be used in any type of application.

13. What is the startup class of dot net core?

Startup class is the entry point of dot net core application. All dot net core applications must have this class. This class is used to configure the application. The call of this class is configured in the program main function. The name of the class can be defined by yourself.

14. What is the function of the configure method of the startup class?

This method defines how the entire application responds to HTTP requests. It has several important parameters, application builder, Hosting environment, logo factory, here we can configure some middleware to handle path, authentication and session, etc.

15. What is middleware (Middleware)?

Middleware is software that is assembled into the application pipeline to process requests and responses. Per component: Choose whether to pass the request to the next component in the pipeline. Work can be performed before and after the next component in the pipeline is called. Request delegates are used to build request pipelines and process each HTTP request. Request delegates are configured using the Run, Map, and Use extension methods. A separate request delegate can be specified in an inline anonymous method (known as inline middleware), or it can be defined in a reusable class. These reusable classes and inline anonymous methods are middleware or middleware components. Each middleware component in the request flow is responsible for calling the next component in the pipeline and, if appropriate, chain-shorting.

16. What are the usage scenarios of middleware?

Authentication, session storage, logging, etc. In fact, our Asp.net core project itself already contains a lot of middleware. For example, identity authentication middleware UseAuthorization() and other series

17. List the official middleware commonly used?

Exception/error handling When the application is running in the development environment: The developer exception page middleware (UseDeveloperExceptionPage) reports application runtime errors. The Database Errors page middleware reports database runtime errors. When the application is running in the production environment: Exception handler middleware (UseExceptionHandler) catches exceptions thrown in the following middleware. The HTTP Strict Transport Security (HSTS) middleware (UseHsts) adds the Strict-Transport-Security header.
HTTPS Redirection Middleware (UseHttpsRedirection) redirects HTTP requests to HTTPS.
The static file middleware (UseStaticFiles) returns static files and simplifies further request processing.
The Cookie Policy middleware (UseCookiePolicy) enables the app to comply with EU General Data Protection Regulation (GDPR). Routing middleware (UseRouting) for routing requests.
Authentication middleware (UseAuthentication) Attempts to authenticate users before allowing them to access secure resources.
Authorization middleware (UseAuthorization) used to authorize users to access secure resources.
Session middleware (UseSession) establishes and maintains session state. If your app uses session state, call the session middleware after the cookie policy middleware and before the MVC middleware.
Endpoint routing middleware for adding Razor Pages endpoints to the request pipeline (UseEndpoints with MapRazorPages).

18. What is the execution order of middleware?

Exception/Error Handling
HTTP Strict Transport Security
HTTPS Redirection
Static File Server
Cookie Policy Enforcement
Authentication
Session
MVC

19. What is the difference between the use and run methods of application builder?

Both of these methods are called in the configure method of the start up class. Both are used to add middleware to the application request pipeline. The Use method can call the addition of the next middleware, while run does not.

20. What is the function of the map extension in the dot net core pipeline?

Different middleware can be added for different paths.

public void Configure(IApplicationBuilder app)
 {
    
    
 	app.Map("/path1", Middleware1);
 	app.Map("/path2", Middleware2);
 }

21. How is the path in dot net core handled?

Path handling is the mechanism used to find handler functions for incoming requests. All paths are registered at the beginning of function execution.
There are two main path processing methods, regular path processing and property path processing. Conventional path processing is to set the call path in the way of MapRoute, and attribute path processing refers to setting a path attribute above the calling function.

22. What are the common project files in the dot net core project

global, launch setting,app settings,bundle config,bower, package。

23. What is the implementation principle of dependency injection?

To implement DI, the core lies in the dependency injection container IContainer, which has the following functions
①. (container) saves the collection of available services // specific objects, classes, and interface services to be used
②. (registration) provides a Ways to bind various components with the services they depend on; // Add... function or containerBuilder.Register function,
③. (parsing point) provides a way for the application to request the configured object: Constructor injection, attribute injection. At runtime, the framework will construct instances through reflection layer by layer, and finally get a complete object

24. How to set IP address and port number for ASP.NET Core project?

You can use the launchSettings configuration file under the Properties folder to configure different startup methods, and configure the IP and port number respectively.

Guess you like

Origin blog.csdn.net/weixin_45091053/article/details/128060958
Recommended