我需要获取请求的时间来版本化一些数据库记录以及将在整个请求中创建的其他记录。
我现在无法使用DateTime,因为我希望在整个请求过程中可以访问相同的时间。
我似乎无法在HTTPContext类中找到任何帮助我的东西。
答案 0 :(得分:3)
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);
}
}
您必须在Startup.Configure
中添加此中间件:
app.UseMiddleware<RequestTimeMiddleware>();
您可以访问请求时间,如:
var httpRequestTimeFeature = HttpContext.Features.Get<IHttpRequestTimeFeature>();
if (httpRequestTimeFeature != null)
{
var requestTime = httpRequestTimeFeature.RequestTime;
}
HttpContext.Items["RequestTime"] = DateTime.Now;
如果我没错,你也可以将它存储在作用域服务(services.AddScoped<YourService>()
)中,这将在整个请求中有效。
我不知道是否存在内置于ASP.NET Core中的请求时间。
你也可以在MVC过滤器中设置它,但我认为这在较低级别(HTTP请求管道)中更有效。