【问题标题】:Get explicit url entered in browser with asp.net core使用 asp.net core 获取在浏览器中输入的显式 url
【发布时间】:2019-04-24 10:16:37
【问题描述】:

我正在开发一个在客户端上使用 ReactJS 的 ASP.NET Core 2.1 应用程序,并希望记录在浏览器中显式输入的 url 以进行跟踪。例如,我想知道用户何时明确输入:http://myapp.com/http://myapp.com/contact; http://myapp.com/help;等等...在浏览器中。一旦用户已经使用 Javascript 在http://myapp.com 中,我就可以跟踪他们何时点击各种链接,但是当用户直接在浏览器中输入它(或点击来自谷歌搜索的链接)时,我' m 目前无法追踪。

我一直在研究 url 中间件重写以及试图找到一种从 Startup 类中的 ConfigureServices 之类的东西访问 HttpContext 的方法,但我无法弄清楚这一点。

任何帮助将不胜感激。

【问题讨论】:

  • 尝试使用IHttpContextAccessor:例如httpContextAccessor.HttpContext.Request.Host.Value; Register it 来自:services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

标签: asp.net-core asp.net-core-2.1


【解决方案1】:

编写中间件相当简单,稍微改编 Microsoft Doc 中的示例将记录 URL。

app.Use(async (context, next) =>
{
    var logger = new MyLogger();
    var requestPath = context.Request.Path;
    logger.Log(requestPath);
    await next.Invoke();
});

但是,我认为无法从 HttpContext 中辨别 URL 是否输入到浏览器地址栏中,而不是任何旧的 GET 请求。

【讨论】:

  • 就像你提到的,这会抓取并记录每个请求。需要找到一种方法来输入浏览器 url,或者至少将其过滤掉。
【解决方案2】:

您可以检查Referer Header。 Asp.Net Core 有一个 http 扩展库,它有一个扩展方法来获取类型化的标头。

添加这个:

using Microsoft.AspNetCore.Http.Extensions;

然后使用 HttpContext 上的 GetTypedHeaders() 扩展访问Referer,这些是一些属性:

httpContext.Request.GetTypedHeaders().Referer.AbsolutePath
httpContext.Request.GetTypedHeaders().Referer.AbsoluteUri
httpContext.Request.GetTypedHeaders().Referer.Authority
httpContext.Request.GetTypedHeaders().Referer.Host
httpContext.Request.GetTypedHeaders().Referer.PathAndQuery

说我们的引用网址是这样的:

http://localhost:4200/profile/users/1?x=1

以上属性将具有以下值:

/profile/users/1
http://localhost:4200/profile/users/1?x=1
localhost:4200
localhost
/profile/users/1?x=1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-29
    • 2010-10-19
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    相关资源
    最近更新 更多