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

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