请不要使用AddHttpContextAccessor()
在 Blazor 服务器中。
我在.Net6中使用以下方法:
我首先按如下方式修改_Host.cshtml文件。
@{
var myCookie = HttpContext.Request.Cookies["CookieName"];
}
<component type="typeof(App)" render-mode="ServerPrerendered" param-AccessToken="myCookie" />
我将 Cookie 信息放入 myCookie 变量中,并将其分配给组件的param-AccessToken
.
然后我去App.razor
文件并定义AccessToken
变量作为级联值。如下:
<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; }
}
最后,任何需要 Cookie 信息值的组件只需将其定义为级联参数即可。例如,我创建一个名为ShowToken.razor
并将其代码如下:
@page "/showtoken"
<p>This is a part of Cookie info @(AccessToken != null ? AccessToken.Substring(0,30) : "(null)")</p>
@code {
[CascadingParameter(Name = "AccessToken")] public string AccessToken { get; set; }
}