0

我想捕獲ASP.NET Core Web API項目中的路由錯誤。ASP.NET核心Web API:捕獲路由錯誤

具體而言,通過路由錯誤,我的意思是,例如: 在控制器我只有:

// GET api/values/5 
[HttpGet("{id}")] 
public string Get(int id) 
{ 
    return "value"; 
} 

但要求是:

api/values/5/6 

404自動地返回,但我希望能夠在代碼中處理這個問題(即調用某種異常處理例程)。

我曾嘗試沒有成功三種不同的方法:

在ConfigureServices(IServiceCollection服務),我說:

services.AddMvc(config => 
{ 
    config.Filters.Add(typeof(CustomExceptionFilter)); 
}); 

這樣就捕捉到控制器中發生的錯誤(例如,如果我把擲( )在上面的Get(id)方法中),但沒有路由錯誤。我認爲這是因爲找不到匹配的控制器方法,所以錯誤在中間件管道中傳播。

在試圖進一步處理錯誤了管道我想...

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
    loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
    loggerFactory.AddDebug(); 

    app.UseExceptionHandler(
     options => 
     { 
      options.Run(
      async context => 
      { 
       var ex = context.Features.Get<IExceptionHandlerFeature>(); 
       // handle exception here 
      }); 
     }); 

    app.UseApplicationInsightsRequestTelemetry(); 
    app.UseApplicationInsightsExceptionTelemetry(); 
    app.UseMvc(); 
} 

我也試過:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
    loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
    loggerFactory.AddDebug(); 

    app.Use(async (ctx, next) => 
     { 
      try 
      { 
       await next(); 
      } 
      catch (Exception ex) 
      { 
       // handle exception here 
      } 
     }); 

    app.UseApplicationInsightsRequestTelemetry(); 
    app.UseApplicationInsightsExceptionTelemetry(); 
    app.UseMvc(); 
} 

上述無論出現時發生了錯誤的路由被調用。我採取了錯誤的做法嗎?或者,如果其中一種方法真的有效?

任何建議將非常感激。

感謝

克里斯

PS。我對ASP.NET Web API相對來說比較新,所以請原諒我在哪裏可能會使用一些錯誤的術語。

回答

3

您可以使用UseStatusCodePages擴展方法:

app.UseStatusCodePages(new StatusCodePagesOptions() 
{ 
    HandleAsync = (ctx) => 
    { 
      if (ctx.HttpContext.Response.StatusCode == 404) 
      { 
       //handle 
      } 

      return Task.FromResult(0); 
    } 
}); 

編輯

app.UseExceptionHandler(options => 
{ 
     options.Run(async context => 
     { 
      var ex = context.Features.Get<IExceptionHandlerFeature>(); 
      // handle 
      await Task.FromResult(0); 
     }); 
}); 
app.UseStatusCodePages(new StatusCodePagesOptions() 
{ 
    HandleAsync = (ctx) => 
    { 
      if (ctx.HttpContext.Response.StatusCode == 404) 
      { 
       // throw new YourException("<message>"); 
      } 

      return Task.FromResult(0); 
    } 
}); 
+0

謝謝,但我寧願如果可能捕捉到一個例外 - 這可能嗎?這裏的方法似乎更像是在事件發生後捕獲結果,而不是在發生問題時捕獲異常。 – cbailiss

+0

爲什麼你需要404結果的例外? –

+0

即使如此,如果你想使用異常看到我的更新。 –