In C# Blazor Server How Can I Send a 404 From A Static Method?

Data Juggler 181 Reputation points
2023-01-26T15:17:28.5433333+00:00

After much work, I finally found a way to get the IP Address of the client in Blazor Server. To do this, I had to use a site called ipify:

<script>
function GetAddress() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "https://api.ipify.org?format=jsonp&callback=DisplayIP";
    document.getElementsByTagName("head")[0].appendChild(script);
};
function DisplayIP(response) {        
    DotNet.invokeMethodAsync('PixelDatabase.Net', 'LogIPAddress', response.ip);
}
</script>

Here is the method invoked:

            /// <summary>
            /// Log IP Address
            /// </summary>     
            [JSInvokable]
            public async void LogIPAddress(string ipAddress)
            {
                // If the ipAddress string exists
                if (TextHelper.Exists(ipAddress))
                {
                    // find the VisitorLog by ipAddress
                    VisitorLog visitorLog = await VisitorLogService.FindVisitorLogByIPAddress(ipAddress);

                    // If the visitorLog object exists
                    if (NullHelper.Exists(visitorLog))
                    {  
                        if (visitorLog.Blocked)
                        {
                            // Not available since this is a Static method
                            // The instance methods of my page have 
                            // NavigationManager injected
                            NavigationManager.NavigateTo("404");
                        }
                    }
                }
            }

I added an endpoint for this:

    endpoints.MapGet("/404", async context =>
    {
        context.Response.StatusCode = 404;
        await context.Response.WriteAsync("404 not found");
    });

This was before I realized the only way I could get the IP was to call a static method from JavaScript.

So my question is:

  1. How can a static method either communicate with the Page instance OR
  2. How can I send a 404 to a blocked IP address from a static method OR
  3. Does Azure have any way to block IP addresses from my VM?

I will back up and state the problem:

Two of my sites (which are demos of open source projects) started getting bombarded by two locations, stayed for 1 second and left. This ruined my Analytics where I might get 0 - 10 visitors a day combined to hundreds per day to each site both from the same two geographic locations, so I know they are bots of some kind.

Even if I write the 'current ip' to my database, I have to have someway to identify the current user from the static method that is also available to the instance Index page.

Any suggestions on how to block or send the user somewhere from the static C# method? If I can route the user to mysite/404 I think the 404 route above should handle it (if the article I read works).

Thanks for any tips as I have run out of ideas.

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,349 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,098 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 53,426 Reputation points
    2023-01-26T16:55:49.5766667+00:00

    not sure why you are using javascript to get the ipaddress. as you are using blazor server, you have access to it from the request. if your server is behind a load balancers, it typically adds an additional header with the ipaddress.

    
    httpContextAccessor.HttpContext.Connection.RemoteIpAddress
    
    0 comments No comments

  2. Zhi Lv - MSFT 31,756 Reputation points Microsoft Vendor
    2023-01-27T03:58:25.25+00:00

    Hi @Data Juggler

    How can a static method either communicate with the Page instance

    You can refer to the following sample to call the Static methods from the JavaScript function:

    <script>
      window.returnArrayAsync = () => {
        DotNet.invokeMethodAsync('BlazorSample', 'ReturnArrayAsync')
          .then(data => {
            console.log(data);
          });
        };
    </script>
    

    Blazor component:

    @page "/call-dotnet-example-1"
    
    <h1>Call .NET Example 1</h1>
    
    <p>
        <button onclick="returnArrayAsync()">
            Trigger .NET static method
        </button>
    </p>
    
    @code {
        [JSInvokable]
        public static Task<int[]> ReturnArrayAsync()
        {
            return Task.FromResult(new int[] { 1, 2, 3 });
        }
    }
    

    More detail information, see Call .NET methods from JavaScript functions in ASP.NET Core Blazor.

    How can I send a 404 to a blocked IP address from a static method

    Since the .NET method is a static method, you can't use the NavigationManager, in this scenario, you can return the checked result to the JavaScript function, then use the window.location.href to refresh the page and change the url. Code like this:

    [Note] in the LogIPAddress method, you need to return a sting result (checked result) to the JavaScript function, refer to the above sample.

                DotNet.invokeMethodAsync('PixelDatabase.Net', 'LogIPAddress', response.ip)
                    .then(str => {
                        alert(str); //get the checked result 
                        //then based on the result to set the window.location.href to change the url. like this: 
                        window.location.href = window.location.protocol + '//' + window.location.host + "/404";
                    });
    

    Does Azure have any way to block IP addresses from my VM?

    This is another question, you'd better to create a new thread with the Azure tag and ask for help from the Azure team.


    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,

    Dillion

    0 comments No comments