我正在学习Blazor,需要一些帮助.

我的Blazor服务器项目需要扩展的身份用户.

我想访问登录显示.文件中的FirstName属性,如下所示.

我发现的大多数讨论都太陈旧了,或者没有解决我的具体问题.

我的项目用户

using Microsoft.AspNetCore.Identity;

namespace MyProject.Data;

public class 我的项目用户 : IdentityUser
{
    [PersonalData]
    public string? FirstName { get; set; }

    [PersonalData]
    public string? LastName { get; set; }
}

我的项目上下文

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace MyProject.Data;

public class 我的项目上下文 : IdentityDbContext<我的项目用户>
{
    public 我的项目上下文(DbContextOptions<我的项目上下文> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}

MyProject的Program.cs

using MyProject.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Components.Authorization;
using MyProject.Areas.Identity;

namespace MyProject
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            var connectionString = builder.Configuration.GetConnectionString("我的项目上下文") ?? throw new InvalidOperationException("Connection string '我的项目上下文' not found.");

            builder.Services.AddDbContext<我的项目上下文>(options => options.UseSqlServer(connectionString));

            builder.Services.AddDefaultIdentity<我的项目用户>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<我的项目上下文>();

            // Add services to the container.
            builder.Services.AddRazorPages();
            builder.Services.AddServerSideBlazor();

            builder.Services.AddHttpContextAccessor();

            builder.Services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<我的项目用户>>();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthorization();

            app.MapBlazorHub();
            app.MapFallbackToPage("/_Host");

            app.Run();
        }
    }
}

一切都很顺利,数据库也更新了等等.

I simply want to access the 我的项目用户's FirstName property here:

登录显示.

<CascadingAuthenticationState>
    <AuthorizeView>
        <Authorized>
            <a href="Identity/Account/Manage">Hello, -->@context.User.Identity?.Name!</a>
            <form method="post" action="Identity/Account/Logout">
                <button type="submit" class="nav-link btn btn-link">Log out</button>
            </form>
        </Authorized>
        <NotAuthorized>
            <a href="Identity/Account/Register">Register</a>
            <a href="Identity/Account/Login">Log in</a>
        </NotAuthorized>
    </AuthorizeView>
</CascadingAuthenticationState>

LoginDisplay在MainLayout.razor中使用

@using Microsoft.AspNetCore.Identity;
@using MyProject.Data;

@inherits LayoutComponentBase

@inject UserManager<我的项目用户> UserManager;
@inject AuthenticationStateProvider GetAuthenticationStateAsync

<PageTitle>MyProject</PageTitle>

<div class="page">
    <div class="sidebar">
        <NavMenu />
    </div>

    <main>      
        <div class="top-row px-4">
            <LoginDisplay />
            <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
        </div>

        <article class="content px-4">
            @Body
        </article>
    </main>
</div>

如有任何帮助,我们不胜感激.

推荐答案

我们需要在MyProjectUser类中添加自定义属性,并运行以下命令.

PM> Add-Migration FirstName  -Context 'MyProjectContext'
PM> Update-Database  -Context 'MyProjectContext'

然后我导航到数据库中的数据,添加我的名字和姓氏.

enter image description here

我的测试结果

enter image description here

我的LoginDisplay.razor

@using blazorfirstname.Areas.Identity.Data
@using Microsoft.AspNetCore.Identity
@inject UserManager<MyProjectUser> userManager
@inject AuthenticationStateProvider authenticationStateProvider

<AuthorizeView>
    <Authorized>
        <a href="Identity/Account/Manage">Hello, @GetFirstNameAsync() !</a>
        <form method="post" action="Identity/Account/Logout">
            <button type="submit" class="nav-link btn btn-link">Log out</button>
        </form>
    </Authorized>
    <NotAuthorized>
        <a href="Identity/Account/Register">Register</a>
        <a href="Identity/Account/Login">Log in</a>
    </NotAuthorized>
</AuthorizeView>


@code {
    private string firstName;

    protected override async Task OnInitializedAsync()
    {
        var authenticationState = await authenticationStateProvider.GetAuthenticationStateAsync();
        var user = await userManager.GetUserAsync(authenticationState.User);
        firstName = user?.FirstName;
    }

    private string GetFirstNameAsync()
    {
        return firstName ?? string.Empty;
    }
}

我的MyProjectUser.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace blazorfirstname.Areas.Identity.Data;

// Add profile data for application users by adding properties to the MyProjectUser class
public class MyProjectUser : IdentityUser
{
    [PersonalData]
    public string? FirstName { get; set; }
    [PersonalData]
    public string? LastName { get; set; }
}

Csharp相关问答推荐

C#如何克服getter的接口空性

在Microsoft XNA框架(MonoGame)中旋转相机

利用.NET 8中的AddStandardResilienceDeliveries和AddStandardHedgingDeliveries实现Resiliency

LINQ无法翻译SQLFunctions方法

Elasticsearch:当我try 使用c#将嵌套对象添加到filter中时出现问题

如何在Visual Studio代码中更改大括号模式{},用于C#语言

在LINQ Where子句中使用新的DateTime

(乌龙)1&#比c#中的UL&#慢吗?

更新产品但丢失产品ASP.NET Core的形象

C#EF Core WHERE IN LINQ FROM LIST WITH.CONTAINS不返回任何内容

C#普罗米修斯指标

在Windows Plesk上发布ASP.NET Core 7 Web API-错误:无法加载文件或程序集';Microsoft.Data.SqlClient';

C#多键字典和TryGetValue

在ASP.NET Core 8 MVC中本地化共享视图

Azure Functions v4中的Serilog控制台主题

JsonPath在Newtonsoft.Json';S实现中的赋值

C#中使用ReadOnlySpan的泛型类型推理

数据库操作预计影响1行,但实际影响0行; after _dbContext.SaveChanges();

在Unity C#中按键点击错误的参数

.NET文档对继承的困惑