Blazor get absolute URL from within the class

Kuler Master 386 Reputation points
2025-01-20T13:57:47.14+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

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,756 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,654 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
367 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Ruikai Feng - MSFT 2,596 Reputation points Microsoft Vendor
    2025-01-21T02:02:01.08+00:00

    As stated in the document:

    HttpContext can be used as a cascading parameter only in statically-rendered root components for general tasks, such as inspecting and modifying headers or other properties in the App component (Components/App.razor). The value is always null for interactive rendering.

    You could get the absolute URL with NavigationManager,for example:

    public class MyService
    {
       public  MyService(NavigationManager navigationManager) 
        {
            _navigationManager = navigationManager;
        }
        private readonly NavigationManager _navigationManager;
        public string GetUri()
        {
            var currentUri = _navigationManager.Uri;
            return currentUri;
        }
    }
    

    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.

    Best regards,

    Ruikai Feng

    0 comments No comments

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.