在ASP.NET Core 2.1中获取请求时间

5

我需要获取请求的时间,以便对某些数据库记录和在请求期间创建的其他记录进行版本控制。

我不能使用DateTime.now,因为我希望在整个请求期间访问相同的时间。

我似乎找不到HTTPContext类中的任何有用信息来帮助我。


为什么在创建请求之前不能使用日期时间变量,例如requestTime = DateTime.Now(),并在整个请求中使用requestTime来版本化记录? - nobody
你可以在中间件或其他地方使用 DateTime.Now 将其添加到 HttpContext.Items 中。 - Konrad
1
如果我没记错的话,您也可以使用 HttpContext.Features - Konrad
1个回答

10

使用HttpContext.Features和HTTP请求管道中间件

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

HttpContext.Items["RequestTime"] = DateTime.Now;

如果我没记错的话,您还可以将其存储在您的作用域服务中(services.AddScoped<YourService>()),这样它将在整个请求期间有效。

我不知道ASP.NET Core中是否内置了请求时间,但是您也可以在MVC过滤器中设置它,但我认为在更低级别的HTTP请求管道中设置更为有效。


1
谢谢回答。这看起来很合理,我会尝试实现它。我很惊讶没有内置时间戳。 - Christopher Edwards
@ChristopherEdwards 你应该在官方仓库上提问,或许会得到一个更好的回答,来自那些正在处理HTTP相关事务的人。 - Konrad
@ChristopherEdwards 这里有一个类似的东西 https://github.com/aspnet/HttpAbstractions/blob/87cd79d6fc54bb4abf07c1e380cd7a9498a78612/src/Microsoft.AspNetCore.Http/Features/HttpRequestIdentifierFeature.cs - Konrad
1
看起来像是一个时间,但是经过了base32编码,这个时间被封装在private static long _requestId中。这应该会给你一个唯一的请求ID。 - Konrad
HttpContext.TraceIdentifier 似乎是 ASP.NET Core 公开暴露的唯一东西。 - Konrad
1
@ChristopherEdwards,它在asp.net MVC中可用,但未移植到核心。https://learn.microsoft.com/en-us/dotnet/api/system.web.httpcontext.timestamp?view=netframework-4.8 - Bronumski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接