.net core 2.0 API 忽略无效路由的中间件
.net core 2.0 API ignore middleware for invalid routing
我有一些验证中间件,如果某些数据丢失,return会给出特定的响应。
当我使用无效的 URL 进行调用时,正在执行中间件,并在响应中发送错误,但错误指出验证问题,而不是 URL无效。
所以我的问题是,我如何设置配置方法,以便任何无效的 URL 不应该执行中间件并且显然 return 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。
我有一些验证中间件,如果某些数据丢失,return会给出特定的响应。
当我使用无效的 URL 进行调用时,正在执行中间件,并在响应中发送错误,但错误指出验证问题,而不是 URL无效。
所以我的问题是,我如何设置配置方法,以便任何无效的 URL 不应该执行中间件并且显然 return 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。