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.

1
  • Try using the IHttpContextAccessor: e.g. httpContextAccessor.HttpContext.Request.Host.Value; Register it via: services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); Commented Nov 21, 2018 at 19:17

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.