mz1378
mz1378

Reputation: 2612

.Net 6 Windows Forms with Blazor services.AddHttpContextAccessor();, httpcontext is null

I am trying to setup Blazor server Authentication system in a windows forms with Blazor app.

I add service services.AddHttpContextAccessor(); in my startup that I added many other services that work.But when I inject this service to a .razor file the service is null.

How to make this work?

Upvotes: 0

Views: 86

Answers (1)

Arani
Arani

Reputation: 1253

In general, I don't recommend using the IHttpContextAccessor anywhere, and it is not something that works with SignalR apps or Blazor apps for that matter. For more info, you can refer to Blazor and shared state and Accessing HttpContext.Items fails.

However, if you have to use the HttpContext then you have to get the desired value(s) from HttpContext when rendering _Host.cshtml and save it in a variable and use that variable in the form of Cascading Parameters in the components in the rest of the program.

For example, I use the following procedure to get HttpContext in Blazor Server web application.

The working method is that I modify the _Host.cshtml file as follows firstly. Here I'm looking for access_token information.

@{
    var token = await HttpContext.GetTokenAsync("access_token");
}

As you can see, I put the access_token information into the token variable and assign it to the component's param-AccessToken. Then I go to the App.razor file and define the AccessToken variable as a Cascading Value. As follows:

<CascadingValue Name="AccessToken" Value="AccessToken">
<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>
@code{
    [Parameter]
     public string AccessToken { get; set; }
 }

Finally, any components that need an AccessToken value just need to define it as a Cascade Parameter. For example, I create a component called ShowToken.razor and put its codes as below:

@page "/showtoken"

<p>This is part of the access token @(AccessToken != null ? AccessToken.Substring(0,30) : "(null)")</p>


@code {
    [CascadingParameter(Name = "AccessToken")] public string AccessToken { get; set; }
}

Upvotes: 1

Related Questions