cra*_*els 4 .net c# asp.net .net-core asp.net-core
我想在ASP.NET Core MVC控制器中获取当前HTTP请求的初始时间戳.这个时间戳曾经可以通过HttpContext.Timestamp访问(在ASP.NET Core之前),但Timestamp似乎不再是HttpContext的属性.
这家酒店搬到了哪里?或者 - 当它不再可用时 - 如何获取HTTP请求的时间戳?
您可以将自己的中间件添加到管道中,从而为请求添加其他数据.例如:
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...
}
Run Code Online (Sandbox Code Playgroud)
然后在管道中:
var requestStartedOn = (DateTime)httpContext.Items["RequestStartedOn"];
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果您打算在其他地方重用此代码,我会把它放在它自己的库中.例如:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后添加扩展方法以使其易于使用:
public static class RequestTimestampMiddlewareExtensions
{
public static IApplicationBuilder UseRequestTimestamp(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestTimestampMiddleware>();
}
}
Run Code Online (Sandbox Code Playgroud)
现在你的Configure方法看起来会好很多:
public void Configure(IApplicationBuilder app)
{
app.UseRequestTimestamp();
//The rest of your code here...
}
Run Code Online (Sandbox Code Playgroud)