웹 API 요청을 기록하는 미들웨어가 있습니다. 아래는 Configuration
내부 의 방법 Startup.cs
입니다. 경우 app.UseMiddleware
앞에 오는 app.UseMvc
경우, 그러나 호출받을 웹 API를 호출 없음 app.UseMiddleware
후 제공 app.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);
}
}
항상 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);
은 반환 될 때 컨트롤러가 요청을 이미 처리 했다는 것 입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다