asp.net-core - 在 ASP.NET core 2.1 中获取请求时间
问题描述
我需要获取请求的时间,以对将在整个请求中创建的一些数据库记录和其他记录进行版本控制。
我现在不能使用 DateTime,因为我希望在整个请求过程中都可以访问相同的时间。
我似乎在 HTTPContext 类中找不到任何可以帮助我的东西。
解决方案
使用 HttpContext.Features 和您的 HTTP 请求管道中间件
public interface IHttpRequestTimeFeature
{
DateTime RequestTime { get; }
}
public class HttpRequestTimeFeature : IHttpRequestTimeFeature
{
public DateTime RequestTime { get; }
public HttpRequestTimeFeature()
{
RequestTime = DateTime.Now;
}
}
// You don't need a separate class for this
public class RequestTimeMiddleware
{
private readonly RequestDelegate _next;
public RequestTimeMiddleware(RequestDelegate next)
{
_next = next;
}
public Task InvokeAsync(HttpContext context)
{
var httpRequestTimeFeature = new HttpRequestTimeFeature();
context.Features.Set<IHttpRequestTimeFeature>(httpRequestTimeFeature);
// Call the next delegate/middleware in the pipeline
return this._next(context);
}
}
您必须将此中间件添加到您的Startup.Configure
:
app.UseMiddleware<RequestTimeMiddleware>();
您可以访问请求时间,例如:
var httpRequestTimeFeature = HttpContext.Features.Get<IHttpRequestTimeFeature>();
if (httpRequestTimeFeature != null)
{
var requestTime = httpRequestTimeFeature.RequestTime;
}
使用 HttpContext.Items
HttpContext.Items["RequestTime"] = DateTime.Now;
services.AddScoped<YourService>()
如果我没记错的话,您也可以将它存储在您的作用域服务( )中,这将在整个请求中有效。
不过,我不知道 ASP.NET Core 中是否内置了请求时间。
您也可以在 MVC 过滤器中设置它,但我认为这在较低级别(HTTP 请求管道)中更有效。
推荐阅读
- vb.net - vb.net框架不使用webBrowser工具自动登录网站
- c# - 加密文件的密钥长度
- pybind11 - 带有需要与静态库链接的 C++ 的 pybind11
- python - 不允许对 tf.Tensor 进行迭代:此函数中禁用了 AutoGraph
- javascript - 如何创建一个以 div id 作为 case 参数的 switch/case 语句?
- ruby-on-rails - 我们可以跳过使用实例变量来呈现 JSON 吗?
- swift - 在接触时播放多种声音 - Xcode Scene Kit
- r - 仅选择日期和数字列
- python - 知道信号是否从 django admin 触发
- android - 为什么颤振 youtube_extractor 包不起作用?