Reputation: 6659
I need to get the time of the request to version some database records and other records that will be created throughout the request.
I can't use DateTime now because I want the same time to be accessible throughout the request.
I can't seem to find anything in the HTTPContext class to help me.
Upvotes: 5
Views: 6170
Reputation: 7247
public interface IHttpRequestTimeFeature
{
DateTime RequestTime { get; }
}
public class HttpRequestTimeFeature : IHttpRequestTimeFeature
{
public DateTime RequestTime { get; }
public HttpRequestTimeFeature()
{
RequestTime = DateTime.Now;
}
}
// You don't need a separate class for this
public class RequestTimeMiddleware
{
private readonly RequestDelegate _next;
public RequestTimeMiddleware(RequestDelegate next)
{
_next = next;
}
public Task InvokeAsync(HttpContext context)
{
var httpRequestTimeFeature = new HttpRequestTimeFeature();
context.Features.Set<IHttpRequestTimeFeature>(httpRequestTimeFeature);
// Call the next delegate/middleware in the pipeline
return this._next(context);
}
}
You have to add this middleware in your Startup.Configure
:
app.UseMiddleware<RequestTimeMiddleware>();
You can access request time like:
var httpRequestTimeFeature = HttpContext.Features.Get<IHttpRequestTimeFeature>();
if (httpRequestTimeFeature != null)
{
var requestTime = httpRequestTimeFeature.RequestTime;
}
HttpContext.Items["RequestTime"] = DateTime.Now;
You can also store it in your scoped service(services.AddScoped<YourService>()
) if I'm not wrong, that will be valid through the entire request.
I'm not aware if there's such thing as request time built-in into ASP.NET Core though.
You can also set this in MVC filters but I think this is more valid in the lower level (HTTP request pipeline).
Upvotes: 10