Monday, April 15, 2024

Ví dụ về Middleware

 namespace EKYC_Core.Middlewares

{

    public class CheckAuthenMiddleware

    {

        private readonly RequestDelegate _next;

        private ILogService? logService;


        public CheckAuthenMiddleware(RequestDelegate next) 

        {

            _next = next;

        }


        public async Task InvokeAsync(HttpContext context)

        {

            //IConfiguration iConfig = context.RequestServices.GetRequiredService<IConfiguration>();

            //List<AuthenConfig> listAuthen = iConfig.GetSection("AuthenConfig")?.Get<List<AuthenConfig>>();


            //IAuthentication authentication = new EKYC_Core.Authentication.Authentication(context.RequestServices, context, listAuthen);

            //try

            //{

            //    await authentication.Validate();

            //}

            //catch (ProjectException ex)

            //{

            //    _ = this.logService.WriteException(ex);

            //    coreResponse = new CoreResponse(ex);

            //    return new JsonResult(coreResponse);

            //}

            //catch (Exception ex)

            //{


            //}





            Stream originalBody = context.Response.Body;


            string requestData = string.Empty;


            try

            {

                var request = context.Request;

                if (request.Method == HttpMethods.Post && request.ContentLength > 0)

                {

                    request.EnableBuffering();

                    var buffer = new byte[Convert.ToInt32(request.ContentLength)];

                    await request.Body.ReadAsync(buffer, 0, buffer.Length);

                    //get body string here...

                    var requestContent = Encoding.UTF8.GetString(buffer);

                    Console.WriteLine(requestContent);

                    request.Body.Position = 0;  //rewinding the stream to 0

                }



                




                using (var memStream = new MemoryStream())

                {

                    context.Response.Body = memStream;


                    await _next(context);


                    memStream.Position = 0;

                    string responseBody = new StreamReader(memStream).ReadToEnd();

                    Console.WriteLine(responseBody);

                    memStream.Position = 0;

                    await memStream.CopyToAsync(originalBody);

                }


            }

            finally

            {

                context.Response.Body = originalBody;

            }



            //var logName = "SYSTEM";

            //this.logService = serviceProvider.GetLogService(logName) ?? serviceProvider.GetLogService("SYSTEM");



            //foreach (var header in context.Request.Headers)

            //{

            //    Console.WriteLine($"Header: {header.Key}: {header.Value}");

            //    //_ = this.logService.WriteMessage($"Header: {header.Key}: {header.Value}");

            //}


            //await _next(context);

        }

    }


    public static class CheckAuthenMiddlewareExtensions

    {

        public static IApplicationBuilder UseCheckAuthen(

            this IApplicationBuilder builder)

        {

            return builder.UseMiddleware<CheckAuthenMiddleware>();

        }

    }

}