Home > Software design >  Where's the property "context" defined in Blazor's AuthorizeRouteView?
Where's the property "context" defined in Blazor's AuthorizeRouteView?

Time:11-29

I have this AuthorizeRouteView section below, and it baffles me as how & where the "context" variable (line 3) is defined. I looked into dotnetcore source code to no avail. Any help would be appreciated!

<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
    <NotAuthorized>
        @if (!context.User.Identity!.IsAuthenticated)
        {
            @*<RedirectToLogin />*@
        }
        else
        {
            <p>You are not authorized to access this resource.</p>
        }
    </NotAuthorized>
</AuthorizeRouteView>

CodePudding user response:

I looked into dotnetcore source code to no avail. Any help would be appreciated!

You won't find it there... the context parameter is a special magic parameter of type AuthenticationState provided when the RenderFragment? NotAuthorized is executed. Where exactly it is defined ? God knows...

Below is a code sample of templated component which may clarify how it works:

TemplatedComponent.razor

@typeparam TItem

@foreach (var item in Items)
{
    @RowTemplate(item);
}

@code {

   [Parameter]
   public RenderFragment<TItem> RowTemplate { get; set; }

   [Parameter]
   public IReadOnlyList<TItem> Items { get; set; }

}

Index.razor

@page "/"


<TemplatedComponent Items="pets">
    <RowTemplate>
        <p>@context.Name</p>

    </RowTemplate>
</TemplatedComponent>



@code{


    List<Pet> pets = new List<Pet>() { new Pet {ID = 1, Name = "Dog"},
                                       new Pet {ID = 2, Name = "Cat" },
                                       new Pet {ID = 3, Name = "Horse"},
                                       new Pet {ID = 4, Name = "Lion"},
                                       new Pet {ID = 5, Name = "Elephant"}};
    public class Pet
    {
        public int ID { get; set; }
        public string Name { get; set; }

    }

}

As you can see the RowTemplate delegate is of type RenderFragment<TItem>, and when it is executed, it exposes the magic context parameter through which you can access the properties of the passed object (Pet). That is the same with the NotAuthorized delegate...

By now I believe you've realized that the identifier context has nothing to do with the HttpContext as suggested by an OP in a comment.

Note: If you still want to know more about how this works under the covers, then a good start should be Templated Razor delegates

CodePudding user response:

@context is a AuthencationState and one way to have it available in your .razor component is by a cascading parameter

You can look for a <CascadingAuthenticationState> tag in your top level App.razor component.

  • Related