2017-09-25 143 views
3

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

此属性在哪里移动?或者 - 当它不再可用时 - 我如何获得HTTP请求的时间戳?

+3

是否有一个原因你不能使用'DateTime.Now'(或'DateTime.UtcNow')? – DavidG

+0

@DavidG:如果前一段时间收到请求会怎么样? – SLaks

+0

@SLaks尽早进行测量,并根据需要将其传递给我。可能不是那么准确,这就是为什么我问问OP是否可以使用它。 – DavidG

回答

5

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

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

谢谢,这是工作。请注意:确保你的控制器接受你发布的数据作为参数,否则控制器将在主体完全发送到服务器之前被调用,并且你将会追逐鬼魂:) –

+1

非常好,我已经更新该帖子是适当的“中间件”并可重用。 :) – DavidG