我有一个中间件用于记录Web API请求。以下是Startup.cs
文件中的Configuration
方法。如果app.UseMiddleware
在app.UseMvc
之前出现,将不会调用任何Web API调用。然而,如果app.UseMiddleware
在app.UseMvc
之后出现,则该中间件将不起作用(即不记录请求)。
下面提供了代码。有什么想法可以解释为什么app.UseMiddleware
会影响app.UseMvc
吗?
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services)
{
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMiddleware<ApiLoggingMiddleware>();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
}
以下是中间件:
public async Task Invoke(HttpContext httpContext, IApiLogService apiLogService)
{
try
{
_apiLogService = apiLogService;
var request = httpContext.Request;
if (request.Path.StartsWithSegments(new PathString("/api")))
{
var stopWatch = Stopwatch.StartNew();
var requestTime = DateTime.UtcNow;
var requestBodyContent = await ReadRequestBody(request);
var originalBodyStream = httpContext.Response.Body;
await SafeLog(requestTime,
stopWatch.ElapsedMilliseconds,
200,//response.StatusCode,
request.Method,
request.Path,
request.QueryString.ToString(),
requestBodyContent
);
}
else
{
await _next(httpContext);
}
}
catch (Exception ex)
{
await _next(httpContext);
}
}
await _next(httpContext)
放在else
外部得到解决。 - renakre