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

时间:2017-09-25 16:13:36

标签: c# asp.net .net asp.net-core .net-core

我想在ASP.NET Core MVC控制器中获取当前HTTP请求的初始时间戳。 这个时间戳曾经是HttpContext.Timestamp可访问的(ASP.NET之前),但Timestamp似乎不再是HttpContext的属性。

这家酒店搬到了哪里?或者 - 当它不再可用时 - 如何获取HTTP请求的时间戳?

1 个答案:

答案 0 :(得分:6)

您可以将自己的中间件添加到管道中,从而为请求添加其他数据。例如:

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...
}

然后在管道中:

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

顺便说一句,如果您打算在其他地方重用此代码,我会把它放在它自己的库中。例如:

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);
    }
}

然后添加一个扩展方法以使其易于使用:

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

现在,您的Configure方法看起来会更好:

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

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