中间件中断了Web API调用

我有一个中间件来记录Web api请求。以下是Configuration中的Startup.cs方法。如果app.UseMiddlewareapp.UseMvc之前,则没有任何Web api调用被调用。但是,如果app.UseMiddlewareapp.UseMvc之后,则中间件不执行任何操作(即记录请求)。

我提供了以下代码。为什么app.UseMiddleware会干扰asp.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);
     }
 }
ppwpp 回答:中间件中断了Web API调用

您必须始终在中间件中调用await _next(httpContext);,否则请求不会正常进行:

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
                   );           
         };
     }
     catch (Exception ex)
     {

     }
     await _next(httpContext);
 }

编辑(中间件的简单说明):
整个中间件的工作方式如下-当请求到达您的应用程序时,它通过中间件管道,每个中间件都必须调用下一个中间件,以便最终将请求发送到控制器。调用await _next(httpContext);时,基本上是在调用管道中下一个中间件的Invoke方法。如果您不致电await _next(httpContext);,则您将停止该请求,该请求不会到达您的控制器。要注意的一件事是,await _next(httpContext);返回时,请求已由您的控制器处理。

本文链接:https://www.f2er.com/3160967.html

大家都在问