Cannot get routeData in IExceptionHandler.TryHandleAsync() for ASP.NET Core 8

jasper.lai 31 信譽點數
2024-02-22T07:30:14.3433333+00:00

I have the following code, and the context. GetRouteData() always return null.
I want to log the controller name and action name when exception occurs.
How can I fix it? GlobalExceptionHandler.cs

public async ValueTask<bool> TryHandleAsync(
	HttpContext context,
	Exception exception,
	CancellationToken cancellationToken)
{

// STEP 0: Get controller name / action name
	var routeData = context. GetRouteData();
	var controllerName = routeData?. Values["controller"]?. ToString();
	var actionName = routeData?. Values["action"]?. ToString();
}

Program.cs

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
else
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

#region Use build-in ExceptionHandler
app.UseExceptionHandler();
#endregion

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
ASP.NET
ASP.NET
.NET Framework 中的一組技術,用於建置 Web 應用程式和 XML Web 服務。
5 個問題
C#
C#
面向物件且類型安全的程式設計語言,其根系於 C 系列語言,並包含元件導向程式設計的支援。
7 個問題
0 則留言 沒有留言
{count} 則投票

2 個回答

排序依據: 最實用
  1. jasper.lai 31 信譽點數
    2024-03-19T06:15:02.21+00:00

    @BruceChen 謝謝 Bruce 老師的回覆.

    會採用 IExceptionHandler.TryHandleAsync(), 主要也是因為看到老師前述回覆的那篇文章.

    但後來發現 Q&A 好像很久沒有人在光顧了, 今天看到老師的 FB 的無界開發者社群 提到 "改版很久的官方技術論壇,繁體中文版已部分上線了,初步都是__開發者__相關標籤,請各位開發者多多利用。" 才又回來看了一下 ^^.

    在 Stackoverflow 提問, 得到的解答是 by Design, 如下連結.

    https://stackoverflow.com/questions/78039198/cannot-get-routedata-in-iexceptionhandler-tryhandleasync-for-asp-net-core-8

    After debug the source code, I found we can't get route data in IExceptionHandler. It's by design. We can find line 143 in ExceptionHandlerMiddlewareImpl.cs file, in github is line 164. In ClearHttpContext method, it set the RouteValues to null. This is the root cause for this issue.

    亦整理了一篇在 GitHub Repository. 如下連結.

    https://github.com/jasper-lai/ExceptionHandler01

    Best Regards,

    有 1 人認為此回答有所幫助。

  2. BruceChen 0 信譽點數 MVP
    2024-03-12T01:51:24.7+00:00