c# - ASP.NET Core MVC 中的 HttpContext.Timestamp 在哪里?

标签 c# asp.net .net asp.net-core .net-core

我想在 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/

相关文章:

c# - 如何使用 Selenium Webdriver 和 Internet Explorer 10 处理 Windows 身份验证?

c# - 在不回发的情况下在更新面板中突出显示 gridview 行

经典 ASP 与 ASP.Net 3.5 中的 CSS?

.net - 使用 SetValue 添加事件处理程序

c# - TryParseExact 返回 false,虽然我不知道为什么

c# - 为 C# Express 用户识别潜在重复代码的好工具是什么?

c# - 在 ASP.NET session 之外使用 HttpApplicationState

c# - startup.cs的Configure方法中如何使用ConfigurationBinder

css - 通过 vb.net 更改 css

c# - 验证数字范围 1300 到 1500 的输入? (使用 Regex 或其他常用方法。)