Rahul Aggarwal
Rahul Aggarwal

Reputation: 291

Change Page URL while redirecting from GlobalError class using IException in .NET Core

My page URL is not changing after I am redirecting from global error class.

This is my code:

public class GlobalExceptionHandler : IExceptionHandler
{
    private readonly IHttpContextAccessor _contextAccessor;
    private readonly ILogger _logger;
    private readonly IWebHostEnvironment _environment;

    public GlobalExceptionHandler(IHttpContextAccessor contextAccessor, ILogger<GlobalExceptionHandler> logger, IWebHostEnvironment environment)
    {
        _contextAccessor = contextAccessor;
        _logger = logger;
        _environment = environment;
    }

    public async ValueTask<bool> 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());
    }
}

Here are the HomeController methods:

 public async Task<ActionResult> Error()
 {
     return View();
 }

Middleware

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

DI Container code

    builder.Services.AddRazorPages();
    builder.Services.AddHttpContextAccessor();
    builder.Services.AddSingleton<IExceptionHandler, GlobalExceptionHandler>();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
    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;
    });

But even after returning a view, it is not changing the URL and showing the same URL on which there is error. I am getting error on Home/Index and after error URL should change to Home/Error, but my URL is still on Home/Index. I am redirected no where even to the Developer Exception Page

Upvotes: 0

Views: 46

Answers (1)

Ruikai Feng
Ruikai Feng

Reputation: 11836

Firstly ,don't inject IHttpContextAccessor which is a scoped service into ExceptionHandler who's lifetime is Singleton

Secondly, remove builder.Services.AddSingleton<IExceptionHandler, GlobalExceptionHandler>(); which is useless

Now on my side,the error was been logged and the request would be redireted to Error page

enter image description here

Upvotes: 0

Related Questions