ASP.NET核心Web API:捕获路由错误 [英] ASP.NET Core Web API: Catching Routing Errors

查看:34
本文介绍了ASP.NET核心Web API:捕获路由错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试捕获ASP.NET Core 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)方法中放了一个throt()),但不会捕获路由错误。我假设这是因为没有找到匹配的控制器方法,所以错误沿中间件管道向上传播。

在尝试进一步沿管道向上处理错误时,我尝试了.

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的新手,因此请原谅我可能使用了稍微错误的术语。

推荐答案

可以使用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);
     }
 });

这篇关于ASP.NET核心Web API:捕获路由错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆