パイプラインに独自のミドルウェアを追加して、要求に追加データを追加することができます。パイプラインの後に続いて
public void Configure(IApplicationBuilder app)
{
//Make sure this code is placed at the very start to ensure it
//executes as soon as possible
app.Use(async (context, next) =>
{
context.Items.Add("RequestStartedOn", DateTime.UtcNow);
await next();
};
//The rest of your code here...
}
:たとえば余談として
var requestStartedOn = (DateTime)httpContext.Items["RequestStartedOn"];
、あなたが他の場所でこのコードを再利用する場合、私はそれ自身のライブラリにそれを置くでしょう。たとえば:その後、
public class RequestTimestampMiddleware
{
private readonly RequestDelegate _next;
public RequestTimestampMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext context)
{
context.Items.Add("RequestStartedOn", DateTime.UtcNow);
// Call the next delegate/middleware in the pipeline
return this._next(context);
}
}
し、使用することを容易にするために拡張メソッドを追加します。
public static class RequestTimestampMiddlewareExtensions
{
public static IApplicationBuilder UseRequestTimestamp(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestTimestampMiddleware>();
}
}
今すぐあなたのConfigure
方法は大きく進歩になります。
public void Configure(IApplicationBuilder app)
{
app.UseRequestTimestamp();
//The rest of your code here...
}
は理由があります'DateTime.Now'(または' DateTime.UtcNow')は使用できません。 – DavidG
@DavidG:しばらく前にリクエストを受信したらどうなりますか? – SLaks
@SLaks必要に応じて測定を早めに行い、必要に応じて回します。正確ではないかもしれないので、私はOPがそれを代わりに使用できるかどうか尋ねています。 – DavidG