There are two ways to pass parameters from the Server part of your Balzor Server App to the front-end part. Here's how you can do that from the _Host.cshtml file
The second way is to create a service class and add it to the DI container, and then inject an instance of the service into your Razor components. The following example decribes how you can capture the HttpContext, extract some data from the HttpContext object, initialize and instantiate the service (UserInfoService
).
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddScoped<UserInfoService>(ctx =>
{
var contextAccessor = ctx.GetService<IHttpContextAccessor>
();
var httpContext = contextAccessor.HttpContext;
string userName = string.Empty;
string email = string.Empty; ;
bool isAuthenticated = false;
if (httpContext.User.Identity.IsAuthenticated)
{
userName = httpContext.User.Identity.Name;
email = httpContext.User.Claims.FirstOrDefault(
c => c.Type ==
ClaimTypes.Email)?.Value;
isAuthenticated =
httpContext.User.Identity.IsAuthenticated;
}
return new UserInfoService
{
Name = userName,
Email = email,
IsAuthenticated = isAuthenticated
};
});
UserInfoService.cs
public class UserInfoService
{
public UserInfoService () { }
public string Name { get; set; }
public string Email { get; set; }
public bool IsAuthenticated { get; set; }
}
Usage
@page "/"
@inject UserInfoService userInfo
<div>@userInfo.Name</div>
<div>@userInfo.Email</div>
<div>@userInfo.IsAuthenticated</div>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />