Search code examples
asp.net-corerazorblazorblazor-server-side

How to only accept POST requests for a page in Blazor .NET 8?


We're building a Server-side Blazor app (based on .NET 8) with two pages: a homepage and a result page. The homepage has an input for 'DateofBirth' and a button to go to the result page.

We want to navigate to the result page ONLY from the homepage with a filled in DateOfBirth. The result page should not be accessible by typing in the URl in the browser or via the back button. If the user would type in the url to the result page directly in the browser, they need to get redirected to the homepage.

Does anyone have an idea on how to force this behaviour? Is there a way to check if the request is a POST and if not, redirect back to another page? Or to stop users from accessing that page if it doesn't originate from the home page?

Thank you very much in advance.


Solution

  • You don't need two routes. Everything in the UI is a component, so use a single page (routed Component) which shows the results component when the state is valid.

    There's no route to Results, so no navigation.

    Here's a quick demo:

    // Results.razor
    <h3>Results</h3>
     
    Here be the results!
    
    @code {
    }
    

    And home:

    @page "/"
    
    <PageTitle>Home</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    @if (_valid)
    {
        <div class="mb-2">
            <button class="btn btn-primary" @onclick="this.OnClick">Go Back</button>
        </div>
        <Results />
    }
    else
    {
        <div class="mb-2">
            <button class="btn btn-primary" @onclick="this.OnClick">Valid Data Submit</button>
        </div>
    }
    
    @code {
        private bool _valid;
    
        private Task OnClick()
        {
            _valid = !_valid;
            return Task.CompletedTask;
        }
    
    }