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.
It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any. ASP.NET Core applications access the HTTPContext through the IHttpContextAccessor interface.
Using Named HttpClient Instances In the Program class, we use the AddHttpClient method to register IHttpClientFactory without additional configuration. This means that every HttpClient instance we create with the CreateClient method will have the same configuration.
NET Core has an easier time working with CPU-intensive tasks and rendering static pages since the in-built IIS server kernel caching makes this process very straightforward. Therefore, . NET core vs node. js performance offers different advantages for various projects.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With