Michael
Michael

Reputation: 11

Blazor Routing: How to prevent direct access to components via URL

I have a blazor wasm application, based on the standard template. In my nav I have several components. Due to the content of the application I want to prevent direct access to the component.

For example preventing direct access to the component "myComponent" by using a link like: https://www.example.com/myComponent

This is necessary as the user has to follow a strict process in the application.

As soon as I remove the @page directive from a component it can not be found via . and navigation doesnt work anymore.

Furthermore: How to hide the component name from the url in the first place?

Looking forward for some hints!

Upvotes: 1

Views: 2237

Answers (2)

SPWwj
SPWwj

Reputation: 21

You can use NavigationManager to redirect the user to other page

example:

@inject NavigationManager NavigationManager
 
@code{
    ....
    protected async override void OnInitialized(){  
         if(!isLogin) {
           NavigationManager.NavigateTo($"/login");
         }
    }
}

also you can check requirement before render the component

Example

@if (isLogin)
{
    <myComponent/>
}

Upvotes: 2

Henk Holterman
Henk Holterman

Reputation: 273854

preventing direct access to the component "myComponent" by using a link like: https://www.example.com/myComponent

You can do that by not adding @page "myComponent"
What you want is the default behaviour already.

How to hide the component name from the url in the first place?

When it is a page you will need something. But you can chose any name you want.

Maybe you can update your question with the distinction between pages and components. And tell us why you don't want which info in URLs.

A page is a component with one or more routing attributes (@page "<url-patern>")

This is necessary as the user has to follow a strict process in the application.

You can build a 'wizard': A main page that maintains a 'step' and shows a specific component based on that value. Use an EventCallback to step forward or backward.

Upvotes: 3

Related Questions