2017-09-25 84 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