From fd74ae20a099121ae1aaae07ff59c9b106d30dd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A4=D1=80=D0=BE=D0=BB=D0=BE=D0=B2?= Date: Wed, 10 Nov 2021 17:04:07 +0500 Subject: [PATCH] CS2-117, CS2-112 Add exception handle middleware. Move middlawares into separate files. --- .../Services/GoogleDriveService.cs | 4 +- .../Middlewares/RequerstTrackerMiddleware.cs | 54 +++++++++++++++++++ .../SimplifyExceptionsMiddleware.cs | 35 ++++++++++++ AsbCloudWebApi/Startup.cs | 37 ++----------- ConsoleApp1/Program.cs | 27 +++------- 5 files changed, 102 insertions(+), 55 deletions(-) create mode 100644 AsbCloudWebApi/Middlewares/RequerstTrackerMiddleware.cs create mode 100644 AsbCloudWebApi/Middlewares/SimplifyExceptionsMiddleware.cs diff --git a/AsbCloudInfrastructure/Services/GoogleDriveService.cs b/AsbCloudInfrastructure/Services/GoogleDriveService.cs index fb1a712d..bf2234b9 100644 --- a/AsbCloudInfrastructure/Services/GoogleDriveService.cs +++ b/AsbCloudInfrastructure/Services/GoogleDriveService.cs @@ -36,8 +36,8 @@ namespace AsbCloudInfrastructure.Services }, Scopes = new[] { DriveService.Scope.Drive }, - DataStore = new FileDataStore(applicationName), - }); + DataStore = new FileDataStore(applicationName),//TODO: replace FileDataStore by thread safe static datastore service + }); public GoogleDriveService() { diff --git a/AsbCloudWebApi/Middlewares/RequerstTrackerMiddleware.cs b/AsbCloudWebApi/Middlewares/RequerstTrackerMiddleware.cs new file mode 100644 index 00000000..83b3ee1f --- /dev/null +++ b/AsbCloudWebApi/Middlewares/RequerstTrackerMiddleware.cs @@ -0,0 +1,54 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace AsbCloudWebApi.Middlewares +{ + public class RequerstTrackerMiddleware + { + private readonly RequestDelegate next; + + public RequerstTrackerMiddleware(RequestDelegate next) + { + this.next = next; + } + + public async Task InvokeAsync(HttpContext context) + { + var service = context.RequestServices.GetRequiredService(); + var requestLog = new AsbCloudApp.Data.RequestLogDto + { + UserLogin = context.User?.Identity.Name, + UserIp = context.Connection.RemoteIpAddress.ToString(), + RequestMethod = context.Request.Method, + RequestPath = context.Request.Path.Value, + Referer = context.Request.Headers["Referer"].ToString(), + }; + { + var userIdString = context.User?.FindFirst("id")?.Value; + if (!string.IsNullOrEmpty(userIdString) && int.TryParse(userIdString, out int userId)) + requestLog.UserId = userId; + } + var sw = System.Diagnostics.Stopwatch.StartNew(); + try + { + await next?.Invoke(context); + sw.Stop(); + requestLog.ElapsedMilliseconds = sw.ElapsedMilliseconds; + requestLog.Status = context.Response.StatusCode; + service.RegisterRequest(requestLog); + } + catch (System.Exception ex) + { + sw.Stop(); + requestLog.ElapsedMilliseconds = sw.ElapsedMilliseconds; + requestLog.Status = context.Response.StatusCode; + service.RegisterRequestError(requestLog, ex); + throw; + } + } + } +} diff --git a/AsbCloudWebApi/Middlewares/SimplifyExceptionsMiddleware.cs b/AsbCloudWebApi/Middlewares/SimplifyExceptionsMiddleware.cs new file mode 100644 index 00000000..deae400d --- /dev/null +++ b/AsbCloudWebApi/Middlewares/SimplifyExceptionsMiddleware.cs @@ -0,0 +1,35 @@ +using Microsoft.AspNetCore.Http; +using System; +using System.Threading.Tasks; + +namespace AsbCloudWebApi.Middlewares +{ + public class SimplifyExceptionsMiddleware + { + private readonly RequestDelegate next; + + public SimplifyExceptionsMiddleware(RequestDelegate next) + { + this.next = next; + } + + public async Task InvokeAsync(HttpContext context) + { + try + { + await next?.Invoke(context); + } + catch (TaskCanceledException ex) + { + Console.WriteLine(ex.Message); + } + catch(Exception ex) + { + if (ex.Message.Contains("Reading the request body timed out due to data arriving too slowly. See MinRequestBodyDataRate.")) + Console.WriteLine("Reading the request body timed out due to data arriving too slowly."); + else + throw; + } + } + } +} diff --git a/AsbCloudWebApi/Startup.cs b/AsbCloudWebApi/Startup.cs index d34649fd..37572326 100644 --- a/AsbCloudWebApi/Startup.cs +++ b/AsbCloudWebApi/Startup.cs @@ -1,4 +1,5 @@ using AsbCloudInfrastructure; +using AsbCloudWebApi.Middlewares; using AsbCloudWebApi.SignalR; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -80,40 +81,8 @@ namespace AsbCloudWebApi app.UseAuthentication(); app.UseAuthorization(); - app.Use(async (context, next) => { - - var service = context.RequestServices.GetRequiredService(); - var requestLog = new AsbCloudApp.Data.RequestLogDto - { - UserLogin = context.User?.Identity.Name, - UserIp = context.Connection.RemoteIpAddress.ToString(), - RequestMethod = context.Request.Method, - RequestPath = context.Request.Path.Value, - Referer = context.Request.Headers["Referer"].ToString(), - }; - { - var userIdString = context.User?.FindFirst("id")?.Value; - if (!string.IsNullOrEmpty(userIdString) && int.TryParse(userIdString, out int userId)) - requestLog.UserId = userId; - } - var sw = System.Diagnostics.Stopwatch.StartNew(); - try - { - await next?.Invoke(); - sw.Stop(); - requestLog.ElapsedMilliseconds = sw.ElapsedMilliseconds; - requestLog.Status = context.Response.StatusCode; - service.RegisterRequest(requestLog); - } - catch(System.Exception ex) - { - sw.Stop(); - requestLog.ElapsedMilliseconds = sw.ElapsedMilliseconds; - requestLog.Status = context.Response.StatusCode; - service.RegisterRequestError(requestLog, ex); - throw; - } - }); + app.UseMiddleware(); + app.UseMiddleware(); app.UseEndpoints(endpoints => { diff --git a/ConsoleApp1/Program.cs b/ConsoleApp1/Program.cs index e453ccdd..561101be 100644 --- a/ConsoleApp1/Program.cs +++ b/ConsoleApp1/Program.cs @@ -1,8 +1,11 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; +using AsbCloudDb.Model; using Google.Apis.Drive.v3.Data; +using Microsoft.EntityFrameworkCore; namespace ConsoleApp1 { @@ -15,25 +18,11 @@ namespace ConsoleApp1 { static void Main(/*string[] args*/) { - var service = new GoogleDriveService(); - - //var files = serviceWrapper.GetAllFiles(); - - // foreach (var file in files) - // { - // var permission = new Permission() { Type = "anyone", Role = "reader"}; - // var createRequest = service.Permissions.Create(permission, file.Id); - // createRequest.Execute(); - // Console.WriteLine(file.WebViewLink); - // } - - var path = "/home/cult/First.xlsx"; - var fileInfo = new FileInfo(path); - var fileStream = System.IO.File.Open(path, FileMode.Open); - var uploadedFileId = service.UploadFile(fileStream, fileInfo.Name, "", "uploaded"); - service.CreatePublicPermissionForFile(uploadedFileId); - var webLink = service.GetFileWebLink(uploadedFileId); - Console.WriteLine(webLink); + var d = "20211102_173407926"; + var dt = DateTime.ParseExact("20211102_173407926", + "yyyyMMdd_HHmmssfff", + CultureInfo.InvariantCulture); + Console.ReadKey(); } } }