【问题标题】:.net core 2.0 API ignore middleware for invalid routing.net core 2.0 API 忽略无效路由的中间件
【发布时间】:2019-01-09 18:33:45
【问题描述】:

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

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

所以我的问题是,我该如何设置 configure 方法,以便任何无效的 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-core middleware


    【解决方案1】:

    简单的请求管道记录器

    试试这个吧……

    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


    【讨论】:

    • 谢谢。这就是我的想法,但我希望既然.net知道路径无效,(我看到404错误)也许有一个属性我可以检查而不是在我们添加新端点时更新if语句.
    猜你喜欢
    • 2018-03-27
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    相关资源
    最近更新 更多