0

I am working on an ASP.NET Core 2.1 application that uses ReactJS on the client and would like to log the urls entered explicitly in the browser for tracking purposes. For example, I would like to know when a user explicitly enters: http://myapp.com/; http://myapp.com/contact; http://myapp.com/help; etc... in the browser. I'm able to track when a user clicks on various links once they're already in http://myapp.com using Javascript, but it's when a user enters it directly in the browser (or clicks on a link from a google search) that I'm currently unable to track.

I've been looking at url middleware rewrite as well as trying to find a way to access the HttpContext from something like ConfigureServices in the Startup class, but I'm not able to figure this out.

Any help would be appreciated.

Los Morales
  • 2,061
  • 7
  • 26
  • 42
  • Try using the `IHttpContextAccessor`: e.g. `httpContextAccessor.HttpContext.Request.Host.Value`; [Register it](https://stackoverflow.com/a/38186047/2477619) via: `services.AddSingleton();` – Felix K. Nov 21 '18 at 19:17

2 Answers2

3

Writing Middleware is fairly straight forward, adapting the example slightly from Microsoft Doc will log the URL.

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

However, I don't think it's possible to discern from the HttpContext whether the URL was entered in the browser address bar, versus any old GET request.

Adam Vincent
  • 3,281
  • 14
  • 38
  • Like you mentioned, this grabs and logs every request. Will need to figure out a way to just get the browser url entered, or at least filter it out. – Los Morales Nov 22 '18 at 17:04
3

You can check for Referer Headers. Asp.Net Core has an http extension library which has an extension method to get the typed headers.

Add this:

using Microsoft.AspNetCore.Http.Extensions;

Then access the Referer using the GetTypedHeaders() extension on a HttpContext, these are some of the properties:

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

Say our Refering Url is like:

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

The above properties will have these values:

/profile/users/1
http://localhost:4200/profile/users/1?x=1
localhost:4200
localhost
/profile/users/1?x=1
Tarik Tutuncu
  • 790
  • 4
  • 12