routes - .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?}");
});
}
谢谢
解决方案
简单的请求管道记录器
试试这个...
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。
推荐阅读
- postgresql - PostgreSQL {call Update Set ...} 得到“SET 处或附近的语法错误”
- python - Sklearn 的 PCA 给出最后一行的“错误”输出
- r - 如何绘制原始数据,但在 ggplot2 R 中使用线拟合的预测值?
- php - Php:符号链接的层级太多?
- java - EMR Spark java应用GC问题
- javascript - 反应加载微调器+ Redux?
- php - 使用 Symfony 4 将用户重定向到匿名用户的登录页面
- nginx - 每个http方法的nginx client_max_body_size
- elasticsearch - ElasticSearch 中的模板
- android - BroadcastReceiver 在模拟器上工作但不在我的设备上