简体   繁体   English

ASP.NET Core MVC中的HttpContext.Timestamp在哪里?

[英]Where is HttpContext.Timestamp in ASP.NET Core MVC?

I would like to get the initial timestamp of the current HTTP request in an ASP.NET Core MVC controller. 我想在ASP.NET Core MVC控制器中获取当前HTTP请求的初始时间戳。 This timestamp used to be accessible (pre ASP.NET Core) by HttpContext.Timestamp , but Timestamp doesn't seem to be a property of HttpContext anymore. 这个时间戳曾经可以通过HttpContext.Timestamp访问(在ASP.NET Core之前),但Timestamp似乎不再是HttpContext的属性。

Where is this property moved to? 这家酒店搬到了哪里? Or - when it is no longer available - how can I get the timestamp of the HTTP request? 或者 - 当它不再可用时 - 如何获取HTTP请求的时间戳?

You can add your own middleware to the pipeline which adds additional data to the request. 您可以将自己的中间件添加到管道中,从而为请求添加其他数据。 For example: 例如:

public void Configure(IApplicationBuilder app)
{
    //Make sure this code is placed at the very start to ensure it 
    //executes as soon as possible
    app.Use(async (context, next) =>
    {
        context.Items.Add("RequestStartedOn", DateTime.UtcNow);
        await next();
    };

    //The rest of your code here...
}

Then later on in the pipeline: 然后在管道中:

var requestStartedOn = (DateTime)httpContext.Items["RequestStartedOn"];

As an aside, if you intend to reuse this code elsewhere, I would put it in it's own library. 顺便说一句,如果您打算在其他地方重用此代码,我会把它放在它自己的库中。 For example: 例如:

public class RequestTimestampMiddleware
{
    private readonly RequestDelegate _next;

    public RequestTimestampMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext context)
    {
        context.Items.Add("RequestStartedOn", DateTime.UtcNow);

        // Call the next delegate/middleware in the pipeline
        return this._next(context);
    }
}

And then add an extension method to make it easy to use: 然后添加扩展方法以使其易于使用:

public static class RequestTimestampMiddlewareExtensions
{
    public static IApplicationBuilder UseRequestTimestamp(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<RequestTimestampMiddleware>();
    }
}

Now your Configure method will look a lot nicer: 现在您的Configure方法看起来会更好:

public void Configure(IApplicationBuilder app)
{
    app.UseRequestTimestamp();

    //The rest of your code here...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM