首页 > 解决方案 > .net core 2.0 API 忽略无效路由的中间件

问题描述

如果某些数据丢失,我有一些验证中间件会返回特定的响应。

当我使用无效的 URL 进行调用时,正在执行中间件,并在响应中发送错误,但错误说明了验证问题,而不是 URL 无效。

所以我的问题是,我如何设置配置方法,以使任何无效的 URL 都不应执行中间件并明确返回 404 错误。

这是我的配置方法:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)//, ITimingLogger timingLogger
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        //app.Use(async (HttpContext context, Func<Task> next) =>
        //{
        //    var timer = new Stopwatch();
        //    timer.Start();
        //    await next();
        //    timer.Stop();
        //    timingLogger.LogElapsedTime(context.Request.Method, context.Request.Path, timer.ElapsedMilliseconds);
        //});

        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMiddleware<RequestResponseLoggingMiddleware>();
        app.UseMiddleware<UnhandledExceptionHandlerMiddleware>();
        app.UseMiddleware<SubscriptionIdValidatorMiddleware>();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

谢谢

标签: routes.net-coremiddleware

解决方案


简单的请求管道记录器

试试这个...

app.Use(async (HttpContext context, Func<Task> next) =>
{
    if (context== null) throw new ArgumentNullException(nameof(context));

    var sw = Stopwatch.StartNew();
    try
    {
        await next(context);
        sw.Stop();

        // do your logging work here

        // for example
        if (httpContext.Response?.StatusCode > 499)
        {
            // 500+ error code is a server error
            // log the error
        }

    }
    catch (Exception ex) when (LogException(context, sw, ex))
    {
        // never caught, because `LogException()` returns false.         
    }
}

然后添加这个静态方法

static bool LogException(HttpContext context, Stopwatch sw, Exception ex)
{
    sw.Stop();

    // log the exception

    return false;
}

请求管道

更直接地回答您的问题,而不仅仅是给您一段代码。我相信您误解了请求管道的行为方式。我会尝试用你的代码来解释它。

app.Use(async (HttpContext context, Func<Task> next) =>
{
    // every single request is currently hitting this middleware
    // even regardless if the URI "exists" or not.
    // to solve this you need to define what is a valid URI

    // for example, validate the path
    if (context.Request.Path != "foo")
    {
        return next();  // break out
    }

    // if we got this far, that means it was a valid URI
    var timer = new Stopwatch();
    timer.Start();

    await next();

    timer.Stop();
    // do work
});

我希望这能说明管道是如何工作的。

请求管道按您列出的顺序执行。目前,您当前的代码中没有任何内容定义什么是“有效” URI



推荐阅读