C# 中间件中断了web api调用
我有一个中间件来记录web api请求。下面是C# 中间件中断了web api调用,c#,asp.net,asp.net-web-api,middleware,C#,Asp.net,Asp.net Web Api,Middleware,我有一个中间件来记录web api请求。下面是Startup.cs中的配置方法。如果app.usembiddleware位于app.UseMvc之前,则不会调用任何web api调用,但是,如果app.usembiddleware位于app.UseMvc之后,则中间件不会执行任何操作(即记录请求) 我在下面提供了代码。你知道为什么app.usembiddleware会与asp.UseMvc发生冲突吗 public void Configure(IApplicationBuilder app, I
Startup.cs
中的配置方法。如果app.usembiddleware
位于app.UseMvc
之前,则不会调用任何web api调用,但是,如果app.usembiddleware
位于app.UseMvc
之后,则中间件不会执行任何操作(即记录请求)
我在下面提供了代码。你知道为什么app.usembiddleware
会与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?}");
});
}
您必须始终调用wait\u 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);
}
编辑(中间件的简单解释):
整个中间件的工作方式如下:当请求到达应用程序时,它通过中间件管道,每个中间件都必须调用下一个中间件,以便最终将请求发送到控制器。调用wait\u next(httpContext)时代码>您基本上是在调用管道中下一个中间件的Invoke方法。如果不调用wait\u next(httpContext)代码>您正在停止请求,但它不会到达您的控制器。需要注意的一点是,当等待下一步时(httpContext)代码>返回,您的控制器已提供请求。谢谢您的回答。你的意思是它不应该在内,否则
?我在我的回答中添加了中间件的简单解释,还有更多信息,请检查您是否可以分享更多中间件的代码,因为从上面的代码中我发现缺少的部分是requestdelegate更多信息还可以查看@Miky谢谢您的评论。通过将wait\u放在下一个(httpContext)中,问题就消失了代码>在else
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);
}