Это мой код: < /p>
Код: Выделить всё
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());
}
}
Код: Выделить всё
public async Task Error()
{
return View();
}
< /code>
промежуточное программное обеспечение < /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>
Но даже после возвращения представления он меняет URL и показывает тот же URL, на котором есть ошибка. Я получаю ошибку в Home/Index Подробнее здесь: https://stackoverflow.com/questions/794 ... tion-in-ne