Get Absolute URL in Blazor class

Kuler Master 406 Reputation points
2025-01-20T14:00:42.1733333+00:00

Hello,

I have a class inside the Services folder.

It contains a LogError(Exception ex) method in which I need the absolute URL in order to get the requested page.

However, I am unable to access the HttpContext.Request.Url or any other method/extension that I tried.

Thank you!

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Blazor
Developer technologies | ASP.NET | Other
Developer technologies | C#
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. P a u l 10,761 Reputation points
    2025-01-20T16:27:25.35+00:00

    Rather than coupling your logging code with ASP.NET a more robust solution could be just pushing any "additional properties" into some global context, like Serilog does with enrichers. Docs

    This code's a bit rough & ready but hopefully puts the point across around how you might achieve this:

    Logger logger = new();
    
    string url = "..."; // Pulled from HttpContext
    
    // With properties:
    using (LogContext.PushProperty("Url", url))
    {
    	logger.LogException(new Exception("Failed (First)!"));
    }
    
    // Without properties:
    logger.LogException(new Exception("Failed (First)!"));
    
    public sealed class Logger
    {
    	public void LogException(Exception e)
    	{
    		var properties = new Dictionary<string, object>
    		{
    			{"Type", e.GetType().ToString()},
    			{"Message", e.Message},
    			{"StackTrace", e.StackTrace}
    		};
    
    		foreach (var property in LogContext.GetProperties())
    		{
    			properties.Add(property.Key, property.Value);
    		}
    
    		// Write somewhere, .e.g.
    		Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(properties));
    	}
    }
    
    public static class LogContext
    {
    	private static readonly List<Property> _properties = new();
    
    	public static Property PushProperty(string key, object value)
    	{
    		var property = new Property { Key = key, Value = value };
    
    		_properties.Add(property);
    
    		return property;
    	}
    
    	public static IEnumerable<Property> GetProperties()
    	{
    		foreach (var property in _properties)
    		{
    			yield return property;
    		}
    	}
    
    	public class Property : IDisposable
    	{
    		public required string Key { get; init; }
    		public required object Value { get; init; }
    
    		public void Dispose()
    		{
    			_properties.Remove(this);
    		}
    	}
    }
    

    If you're familiar with ASP.NET middleware you could create one that pushes all the relevant ASP.NET context properties into LogContext by wrapping the await next.Invoke(); in a using scope like I'm doing above: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-9.0

    0 comments No comments

  2. Bruce (SqlWork.com) 79,526 Reputation points Volunteer Moderator
    2025-01-20T17:21:02.4366667+00:00

    Blazor is a single page app. HttpContext is read only and only contains the url of the page that loaded the Blazor app. To get the navigation url, you inject the NavigationManager, and use it to access the URI.

    0 comments No comments

  3. Anonymous
    2025-01-28T07:35:56.7+00:00

    Hi @Kuler Master,

    According to your description, I suggest you could use the NavigationManager to get the url instead of httpcontext, since the httpcontext.request is not directly available inside the blazor , blazor use the web socket instead of the normal request.

    I suggest you could try below codes and test it at your side to get the url.

    1.Create the logger service:

        public class ErrorLoggerService
        {
            private readonly NavigationManager _navigationManager;
    
            public ErrorLoggerService(NavigationManager navigationManager)
            {
                _navigationManager = navigationManager;
            }
    
            public void LogError(Exception ex)
            {
                var currentUrl = _navigationManager.Uri;  
         
                Console.WriteLine($"Error occurred on page: {currentUrl}");
                Console.WriteLine($"Exception: {ex.Message}");
            }
        }
    
    

    2.Resiger it inside the program.cs

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddScoped<ErrorLoggerService>();
    ....
    
    

    3.Use it inside the component.

    @page "/counter"
    @inject BlazorApp2.ErrorLoggerService ErrorLogger
    
    <PageTitle>Counter</PageTitle>
    
    <h1>Counter</h1>
    
    <p role="status">Current count: @currentCount</p>
    
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    
    
    <button @onclick="TriggerError">Trigger Error</button>
    
     
    @code {
        private int currentCount = 0;
    
        private void IncrementCount()
        {
            currentCount++;
        }
    
        private void TriggerError()
        {
            try
            {
                throw new InvalidOperationException("Something went wrong!");
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
            }
        }
    }
    
    

    Test result:

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

     

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  4. Danny Nguyen (WICLOUD CORPORATION) 1,030 Reputation points Microsoft External Staff
    2025-08-25T08:51:04.9966667+00:00

    Hi,

    In ASP.NET Core, HttpContext.Request.Url was replaced with properties like HttpContext.Request.Scheme, HttpContext.Request.Host, HttpContext.Request.Path, and HttpContext.Request.QueryString. You need to combine these to build the full URL.In Blazor WebAssembly, there is no HttpContext at all because the code executes in the browser. Instead, Blazor gives you NavigationManager to read and manipulate the current URI ASP.NET Core Blazor routing and navigation | Microsoft Learn

    • In Blazor Server, you can access HttpContext, but only when you flow it into your service properly.
    • In Blazor WebAssembly, there is no server HttpContext, so you need to use NavigationManager to obtain the current URL.

    For Blazor Server Inject IHttpContextAccessor into your service and construct the URL like this:

    using Microsoft.AspNetCore.Http;
     
    public class MyService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
     
        public MyService(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
     
        public string? GetAbsoluteUrl()
        {
            var request = _httpContextAccessor.HttpContext?.Request;
            if (request == null) return null;
     
            return $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";
        }
    }
    

    Don’t forget to register the accessor in Program.cs:

    builder.Services.AddHttpContextAccessor();
    

    If you’d like more details about working with HttpContext in ASP.NET Core, Microsoft explains it here: Access HttpContext in ASP.NET Core | Microsoft Learn.


    For Blazor WebAssembly Use NavigationManager (it’s built-in for exactly this purpose):

    using Microsoft.AspNetCore.Components;
     
    public class MyService
    {
        private readonly NavigationManager _navigationManager;
     
        public MyService(NavigationManager navigationManager)
        {
            _navigationManager = navigationManager;
        }
     
        public string GetAbsoluteUrl()
        {
            return _navigationManager.Uri; // full URL of the current page
        }
    }
    

    Hope this helps, feel free to reach out if there's any problem


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.