Dies ist mein Code: < /p>
Code: Select all
public class GlobalExceptionHandler : IExceptionHandler
{
private readonly IHttpContextAccessor _contextAccessor;
private readonly ILogger _logger;
private readonly IWebHostEnvironment _environment;
public GlobalExceptionHandler(IHttpContextAccessor contextAccessor, ILogger logger, IWebHostEnvironment environment)
{
_contextAccessor = contextAccessor;
_logger = logger;
_environment = environment;
}
public async ValueTask TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
if (exception != null)
{
var response = new ExceptionResponse()
{
ErrorDatetime = DateTime.Now.ToString(),
ExceptionMessage = exception.Message,
Title = "Something went wrong",
ErrorPath = httpContext.Request.Path,
Method = httpContext.Request.Method,
UserLogin = httpContext.Session?.GetString("userid"),
ErrorStackTrace = exception.StackTrace
};
httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
httpContext.Response.ContentType = "application/json";
LogException(response);
// Return the error response as JSON
//await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(response), cancellationToken);
httpContext.Response.Redirect("/Home/Error");
return true; // Indicates that the exception was handled
}
return false; // Indicates that the exception was not handled
}
private void LogException(ExceptionResponse exceptionResponse)
{
string filepath = Path.Combine(_environment.WebRootPath, "logs");
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
StringBuilder sb = new StringBuilder();
sb.AppendLine($"Date & Time: --> {exceptionResponse.ErrorDatetime}");
sb.AppendLine($"User: --> {exceptionResponse.UserLogin}");
sb.AppendLine($"Error Message:--> {exceptionResponse.ExceptionMessage}");
sb.AppendLine($"Function:--> {exceptionResponse.Method}");
sb.AppendLine($"Error Path:--> {exceptionResponse.ErrorPath}");
sb.AppendLine($"Stack Trace:--> {exceptionResponse.ErrorStackTrace}");
File.AppendAllText(Path.Combine(filepath, $"log_{DateTime.Now:ddMMyyyy}.txt"), sb.ToString());
}
}
Code: Select all
public async Task Error()
{
return View();
}
< /code>
Middleware < /p>
app.UseSession();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseRouting();
app.UseStaticFiles();
// app.UseExceptionHandler(_ => { });
app.UseHttpsRedirection();
// app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.UseAuthorization();
app.MapRazorPages();
app.Run();
< /code>
di Containercode < /p>
builder.Services.AddRazorPages();
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton();
builder.Services.AddExceptionHandler();
var connectionString = builder.Configuration.GetConnectionString("connection");
builder.Services.AddScoped(provider => new DataService(connectionString));
builder.Services.AddRazorPages().AddRazorRuntimeCompilation();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});