首页 > 解决方案 > 在 ASP.NET core 2.1 中获取请求时间

问题描述

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

我现在不能使用 DateTime,因为我希望在整个请求过程中都可以访问相同的时间。

我似乎在 HTTPContext 类中找不到任何可以帮助我的东西。

标签: asp.net-core

解决方案


使用 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 请求管道)中更有效。


推荐阅读