.Net Core practice of using Web Api middleware (a)

Introduction: into the pit .net core from mid-2019 has been more than six months, on the whole, although the multi-sensory pits, but it is quite fragrant with. What I do not like to write this kind of practice sharing or fill hole record of the blog, because preliminary practice pit and more, the article certainly there will be a variety of errors, with excellent article compared to other people, if I write something there is nothing the value of. However, since the pit .net core, this idea began to slowly change, after all, I rely on others to solve the problem of the article are not textbook-like existence, but it is to use. So, put their records out of practice, on the one hand is to consolidate and improve their own technology stack, the other can help other people, or to discuss with others, not too wheels behind closed doors, entertain it. .net core web api practice records began from the use of middleware it.

1, the necessary knowledge base

In reading this article, I hope that readers already know the interface of the inverter and covariance, generic, commission and other knowledge (personally think that this is the necessary knowledge to understand the various .net framework), but also know .net core dependency injection, relevant content life cycle (before the garden several chiefs, for this has a very good explanation, I will not be introduced, there is a need of children's shoes can leave a message, I provide a connection).

2, .net core webapi project in the configuration of middleware

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMiddleware<RequestMiddleware>();           
            app.UseMvc();
        }

  In Startup.cs project file, locate the Configure method, plus app.UseMiddleware <RequestMiddleware> (); RequestMiddleware here is a custom middleware, we can simply look UseMiddleware definition:

 

 TMiddleware is a generic, use UseMiddleware transfer is custom middleware.

3, custom implementation of middleware

I am sorry I could not find a decompiler UseMiddleware implementation methods, but in conjunction with the official online presentation ( https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/write?view=aspnetcore- 3.1 ), custom middleware needs to receive a RequestDelegate constructor object is on a delegate of HttpRequest, also called a need  Invoke or a  InvokeAsync common method for the write HttpRequest preprocessing logic. In my project, I use it to carry out pre-processing parameters, log preprocessing, preprocessing and forwarding Session request.

public class RequestMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IConfig config;

        public RequestMiddleware(RequestDelegate next, IConfig config)
        {
            _next = next;
            this.config = config;
        }

        public Task Invoke(HttpContext context)
        {
            context.Request.EnableRewind (); // support context.Request.Body read repeatedly, internal calls EnableBuffering method, or when using the section method or property will be reported error System.NotSupportedException: Specified method is not supported, such as context. Request.Body.Position
            // && context.Request.Path.Value == "/api/Main"
            if (context.Request.ContentLength != null)
            {
                Stream stream = context.Request.Body;
                byte[] buffer = new byte[context.Request.ContentLength.Value];
                stream.Read(buffer, 0, buffer.Length);
                string querystring = Encoding.UTF8.GetString(buffer);

                RequestMiddleParam requestEntity = Newtonsoft.Json.JsonConvert.DeserializeObject<RequestMiddleParam>(querystring);
                if (requestEntity == null)
                {
                    throw new Exception ( "request can not be processed");
                }

                
                string param = Newtonsoft.Json.JsonConvert.SerializeObject(requestMiddleMapParam);        //参数
                // todo parameter check
                byte [] bs = Encoding.UTF8.GetBytes (param); // code parameters into utf8

                //context.Request.Body.Seek(0, SeekOrigin.Begin);
                //context.Request.EnableBuffering();

                var ms = new MemoryStream();
                context.Request.Body = ms;
                context.Request.Body.Write(bs, 0, bs.Length);

                context.Request.Body.Position = 0; // reset pointer context.Request.Body the Stream, or packets A non-empty request body is required error.
            }

            // Call the next delegate/middleware in the pipeline
            return this._next(context);
        }
    }

  It is noted that the constructor method may be used in the Startup.cs in ConfigureServices injection term, the above example is the code IConfig. (There is also a pit, the middleware is to receive services.AddDbContext items via constructor injection, because the life cycle is not the same)

4, pretreatment parameters encountered pit

Post a request to an example, the parameter is Json structure, in order to determine the parameters of a field Json compliance with the rules, it needs to be deserialized, after checking is completed, and then filled into Body serialized object. Note here that the context.Request.EnableRewind (); and context.Request.Body.Position = 0; add two lines of code, because the stream is in the form of reading and rewriting parameters, EnableRewind method supports read repeatedly, and context.Request.Body.Position normalized 0 ensure that after the re-write the parameters body, reported a non-empty request body is required . error.

 

These are the core middleware .net brief, but in fact it's a bit like asp.net role of interceptor to intercept the request to do some pre-processing, for processing, forwarding service request parameters, or even log in checking and other needs, It is a good choice. If you want to understand the students, they are free to seek implementation of UseMiddleware. The next article, I will introduce the use .net core + Redis + Session completed Session pit encountered in distributed shared, welcome to discuss.

 

Guess you like

Origin www.cnblogs.com/BradPitt/p/12146409.html