我想在 ASP.NET Core MVC Controller 中获取当前 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...
}
然后在管道中:
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...
}
关于c# - ASP.NET Core MVC 中的 HttpContext.Timestamp 在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46409709/