CS2-117, CS2-112

Add exception handle middleware.
Move middlawares into separate files.
This commit is contained in:
Фролов 2021-11-10 17:04:07 +05:00
parent fccfd538fc
commit fd74ae20a0
5 changed files with 102 additions and 55 deletions

View File

@ -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()
{

View File

@ -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<AsbCloudApp.Services.IRequerstTrackerService>();
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;
}
}
}
}

View File

@ -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;
}
}
}
}

View File

@ -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<AsbCloudApp.Services.IRequerstTrackerService>();
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<SimplifyExceptionsMiddleware>();
app.UseMiddleware<RequerstTrackerMiddleware>();
app.UseEndpoints(endpoints =>
{

View File

@ -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();
}
}
}