如何在 ASP.NET Core 应用程序中显示和更新自定义身份字段?

2024-03-14

我使用创建了一个 ASP.NET Core 应用程序core 3.1我已经包含了开箱即用的身份验证。我想添加一些自定义字段供我的用户完成,例如Location and Instagram。继此处说明 https://learn.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-3.1#customize-the-model我创建了一个ApplicationUser.cs继承的模型IdentityUser并成功迁移该模型以将字段添加到我的AspNetUsers桌子。到目前为止一切都好。

我想将这些字段添加到我的用户帐户页面。我意识到我看不到用户帐户页面。使用我将缺少的帐户页面添加到我的项目中。然而,当我添加丢失的字段时,它声称无法找到它们,尽管整个项目标识正在使用ApplicationUser按照文档中的说明。

区域/页面/帐户/管理/Index.cshtml

@page
@model IndexModel
@{
    ViewData["Title"] = "Profile";
    ViewData["ActivePage"] = ManageNavPages.Index;
}

<h4>@ViewData["Title"]</h4>
<partial name="_StatusMessage" model="Model.StatusMessage" />
<div class="row">
    HEY
    <div class="col-md-6">
        <form id="profile-form" method="post">
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Username"></label>
                <input asp-for="Username" class="form-control" disabled />
            </div>
            <div class="form-group">
                <label asp-for="Location"></label>
                <input asp-for="Location" class="form-control" />

            </div>
            <div class="form-group">
                <label asp-for="Instagram"></label>
                <input asp-for="Instagram" class="form-control" />

            </div>
            <div class="form-group">
                <label asp-for="Input.PhoneNumber"></label>
                <input asp-for="Input.PhoneNumber" class="form-control" />
                <span asp-validation-for="Input.PhoneNumber" class="text-danger"></span>
            </div>
            <button id="update-profile-button" type="submit" class="btn btn-primary">Save</button>
        </form>
    </div>
</div>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

Location 和 Instagram 都会返回在模型中找不到它们的错误。我是否错过了某个步骤,或者是否需要执行其他操作来添加这些字段?


您应该添加属性Location and Instagram in IndexModel.

更新输入模型Areas/Identity/Pages/Account/Manage/Index.cshtml.cs :

public class InputModel
{
    [Phone]
    [Display(Name = "Phone number")]
    public string PhoneNumber { get; set; }

    public string Instagram { get; set; }

    public string Location { get; set; }

}

Update LoadAsync加载/显示属性的方法:

private async Task LoadAsync(ApplicationUser user)
{
    var userName = await _userManager.GetUserNameAsync(user);
    var phoneNumber = await _userManager.GetPhoneNumberAsync(user);



    Username = userName;

    Input = new InputModel
    {
        PhoneNumber = phoneNumber,

        Instagram=user.Instagram,

        Location = user.Location
    };
}

Update OnPostAsync更新方法Location and Instagram特性:

public async Task<IActionResult> OnPostAsync()
{
    var user = await _userManager.GetUserAsync(User);
    if (user == null)
    {
        return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
    }

    if (!ModelState.IsValid)
    {
        await LoadAsync(user);
        return Page();
    }

    var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
    if (Input.PhoneNumber != phoneNumber)
    {
        var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
        if (!setPhoneResult.Succeeded)
        {
            var userId = await _userManager.GetUserIdAsync(user);
            throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
        }
    }
    if (Input.Instagram != user.Instagram)
    {
        user.Instagram = Input.Instagram;
    }

    if (Input.Location != user.Location)
    {
        user.Location = Input.Location;
    }

    await _userManager.UpdateAsync(user);


    await _signInManager.RefreshSignInAsync(user);
    StatusMessage = "Your profile has been updated";
    return RedirectToPage();
}

最后,修改 Index.cshtml 以包含两个属性:

<div class="form-group">
    <label asp-for="Input.Location"></label>
    <input asp-for="Input.Location" class="form-control" />

</div>
<div class="form-group">
    <label asp-for="Input.Instagram"></label>
    <input asp-for="Input.Instagram" class="form-control" />

</div>

您还可以点击更多细节 。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 ASP.NET Core 应用程序中显示和更新自定义身份字段? 的相关文章

  • 无法继承形状

    为什么我不能使用继承 a 的类Shapes class http msdn microsoft com en us library ms604615 28v vs 90 29 我需要延长Rectangle具有一些方法的类 但我想以与使用相同
  • strlen() 编译时优化

    前几天我发现你可以找到编译时strlen使用这样的东西 template
  • Boost ASIO 串行写入十六进制值

    我正在使用 ubuntu 通过串行端口与设备进行通信 所有消息都必须是十六进制值 我已经在 Windows 环境中使用白蚁测试了通信设置 并得到了我期望的响应 但在使用 Boost asio 时我无法得到任何响应 以下是我设置串口的方法 b
  • ASP.NET MVC 3 中嵌入的 PHP 站点的 IgnoreRoute

    我有一个带有嵌入式 WordPress 博客的 MVC 3 网站 以下所有 url 均通过 MVC 定向 www mysite com www mysite com aboutus www mysite com contactus 我还有一
  • Selenium - C# - Webdriver - 无法找到元素

    在 C 中使用 selenium 我试图打开浏览器 导航到 Google 并找到文本搜索字段 我尝试下面的 IWebDriver driver new InternetExplorerDriver C driver Navigate GoT
  • 混合模型优先和代码优先

    我们使用模型优先方法创建了一个 Web 应用程序 一名新开发人员进入该项目 并使用代码优先方法 使用数据库文件 创建了一个新的自定义模型 这 这是代码第一个数据库上下文 namespace WVITDB DAL public class D
  • 如何向 Mono.ZeroConf 注册服务?

    我正在尝试测试 ZeroConf 示例http www mono project com Mono Zeroconf http www mono project com Mono Zeroconf 我正在运行 OpenSuse 11 和 M
  • 在Page_Load之前处理事件

    我有一个 ASP NET 网页 其中包含大量在页面的 Page Load 事件中处理的代码 我在页面上还有一个下拉框 应该使用新值重新加载页面 但我想在处理整个页面加载代码之前获取这个新值 我正在尝试了解 ASP NET 页面生命周期 我应
  • 为什么这个 makefile 在“make clean”上执行目标

    这是我当前的 makefile CXX g CXXFLAGS Wall O3 LDFLAGS TARGET testcpp SRCS main cpp object cpp foo cpp OBJS SRCS cpp o DEPS SRCS
  • 包恢复失败。回滚包更改 - Serilog.AspNetCore

    我有一个 asp net Core 项目 我正在尝试向其中添加一个记录器 我选择了我在其他项目中使用过的 SeriLog 但是当我尝试添加 Serilog AspNetCore 我得到的软件包版本 2 0 0 包恢复失败 回滚 后端 的包更
  • 如何防止 Blazor NavLink 组件的默认导航

    从 Blazor 3 1 Preview 2 开始 应该可以防止默认导航行为 https devblogs microsoft com aspnet asp net core updates in net core 3 1 preview
  • __doPostBack 重新加载整个页面而不仅仅是 UpdatePanel

    在我的 javascript 中 我有以下行 doPostBack MyPanel MyParam 在后面的代码中 我使用 MyParam 查询数据库并将结果绑定到 MyPanel updatepanel 内的 gridview updat
  • 如何在多线程应用程序中安全地填充数据并 Refresh() DataGridView?

    我的应用程序有一个 DataGridView 对象和一个 MousePos 类型的列表 MousePos 是一个自定义类 它保存鼠标 X Y 坐标 类型为 Point 和该位置的运行计数 我有一个线程 System Timers Timer
  • Xamarin Forms Binding - 访问父属性

    我无法访问页面的 ViewModel 属性以便将其绑定到 IsVisible 属性 如果我不设置 BindingContext 我只能绑定它 有没有办法可以在设置 BindingContext 的同时访问页面的 viewmodel root
  • 调用 .ToArray() 时出现 ArgumentException

    我有一个经常被清除的列表 代码完全是这样的 VisitorAgent toPersist List
  • C++ 指针引用混淆

    struct leaf int data leaf l leaf r struct leaf p void tree findparent int n int found leaf parent 这是 BST 的一段代码 我想问一下 为什么
  • 如何编写一个接受 int 或 float 的 C 函数?

    我想用 C 语言创建一个扩展 Python 的函数 该函数可以接受 float 或 int 类型的输入 所以基本上 我想要f 5 and f 5 5 成为可接受的输入 我认为我不能使用if PyArg ParseTuple args i v
  • JWT - 配置授权服务器并将颁发者设置为其本身

    我正在尝试按照本指南设置授权服务器 http bitoftech net 2014 10 27 json web token asp net web api 2 jwt owin authorization server http bito
  • 如何在 C# 中获取 CMD/控制台编码

    我需要指定正确的代码页来使用 zip 库打包文件 正如我所见 我需要指定控制台编码 在我的例子中为 866 C Users User gt mode Status for device CON Lines 300 Columns 130 K
  • 嵌入式linux编写AT命令

    我在向 GSM 模块写入 AT 命令时遇到问题 当我使用 minicom b 115200 D dev ttySP0 term vt100 时它工作完美 但我不知道如何在 C 代码中做同样的事情 我没有收到任何错误 但模块对命令没有反应 有

随机推荐