关于MVC和Identity的两个问题

2023-12-01

我对身份和 MVC 非常陌生,我正在尝试创建一个 MVC 应用程序作为我的第一个项目。

我已经能够关注一些教程并已成功向我的 ApplicationUser : IdentityUser 类添加其他属性

public class ApplicationUser
    : IdentityUser<string, ApplicationUserLogin,
    ApplicationUserRole, ApplicationUserClaim>
{
    [Required]
    [Display(Name = "UserName")]
    [StringLength(50)]
    public string Handle { get; set; }

    [StringLength(100, ErrorMessage = "Your {0} can be at most {1} characters long.")]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [StringLength(100, ErrorMessage = "Your {0} can be at most {1} characters long.")]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    [Display(Name = "User Creation Date")]
    public DateTime UserCreationDate { get; set; }

    public ApplicationUser()
    {
        this.Id = Guid.NewGuid().ToString();

        // Add any custom User properties/code here
    }

我的问题是:

  1. 我看到在 App_Start.IdentityConfig.cs 中电子邮件被设置为需要唯一的电子邮件,有没有办法将其设置为需要像 Handle 这样的唯一自定义属性?

        var manager = new ApplicationUserManager(new UserStore<ApplicationUser, ApplicationRole, string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };
    
  2. 在 Views.Shared._LoginPartial.cshtml 的部分视图中,它显示使用 User.Identity.GetUserName() 登录应用程序的人员的用户名/电子邮件,是否有一种方法可以引用我的自定义属性之一,例如 FirstName,或处理?

    @using Microsoft.AspNet.Identity
    
    @if (Request.IsAuthenticated)
    {
        using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
        {
        @Html.AntiForgeryToken()
    
        <ul class="nav navbar-nav navbar-right">
            <li>
                @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
            </li>
            <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
        </ul>
        }
    }
    else
    {
        <ul class="nav navbar-nav navbar-right">
            <li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
            <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
        </ul>
    }
    

实施定制UserValidator已经在这里介绍过:如何自定义 Asp.net Identity 2 用户名已采用验证消息?

不要为每个页面请求都访问数据库来显示句柄,而是在登录期间添加声明。

定义您自己的主张:

public static class CustomClaimTypes
{
    public const string Handle = "http://schemas.xmlsoap.org/ws/2014/03/mystuff/claims/handle";
}

在登录过程中,设置声明:

private async Task SignInAsync(ApplicationUser user, bool isPersistent, string password = null)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);

    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

    //Get the handle and add the claim to the identity.
    var handle = GetTheHandle();
    identity.AddClaim(new Claim(CustomClaimTypes.Handle, handle);

    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

然后,通过扩展方法,您可以按照与GetUserName():

public static class IdentityExtensions
{
    public static string GetHandle(this IIdentity identity)
    {
        if (identity == null)
            return null;

        return (identity as ClaimsIdentity).FirstOrNull(CustomClaimTypes.Handle);
    }

    internal static string FirstOrNull(this ClaimsIdentity identity, string claimType)
    {
        var val = identity.FindFirst(claimType);

        return val == null ? null : val.Value;
    }
}

最后,在您看来:

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

关于MVC和Identity的两个问题 的相关文章

  • QTableView 并双击一个单元格

    我正在开发测试用例编辑器 该编辑器包含 USART 传输和接收数据包格式 编辑器是一个表格视图 发送和接收数据包的长度为八个字节 例如 0x01 0x02 0x03 0x08 它在我的第五和第六栏中 现在 我希望此列中的单元格为只读 但是当
  • TestContext.DataRow["MyColumnName"] 的替代品是什么

    在 Net Core 单元测试项目中使用 MSTest 我正在尝试使用 csv 数据源来提供测试方法的数据 以前 我会在 Net Framework 测试项目中使用如下所示的内容 DataSource Microsoft VisualStu
  • "/>

    Error 5 expected Css test css gt gt 我需要给吗 在这里 因为我的解决方案仍然无法正常工作 它开始给出一些其他错误 您需要添加一个等号 如下所示 Css test css gt gt 解释 块将整个语句或块
  • CMake source_group() 无法在分层项目设置中正常工作

    在进行更改以使 CMake 项目具有分层文件夹管理后 source group 似乎不再正常工作 CMake 只是将所有内容转储到默认过滤器中 我尝试了各种正则表达式来从父级获取每个源文件的相对文件路径 甚至对父级 CMakeLists t
  • 关于我的编译器中缺少 stdafx.h(Windows 上的 mingw32)

    我有一个简单的问题 我注意到我的编译器中没有 stdafx h Windows 上的 mingw32 我应该拥有它吗 或者也许有办法绕过它 谢谢阅读 编辑 好的 这是我取出 stdafx h 的所有包含内容后的当前构建日志 http pas
  • 从任务并行库更新 ProgressBar UI 对象

    基本上我想更新 FormMain WindowsForm 上的 ProgressBar UI 对象 我正在使用 NET 4 0 以下是 Form1 Designer cs 中的代码 namespace ProgressBarApp publ
  • “char *”类型的参数与“LPWSTR”类型的参数不兼容

    以前可能有人问过这个问题 但我似乎找不到解决方案 std string GetPath char buffer MAX PATH GetSystemDirectory buffer MAX PATH strcat buffer versio
  • 将函数模板传递给其他函数

    假设我有一个函数可以对任意容器类型 C 11 执行某些操作 template
  • C语言中的积分提升和平衡有什么区别?

    积分提升和平衡有什么区别 我们是否可以总结这两条规则 即在执行任何操作 逻辑运算符 除外 之前 任何类型都至少转换为 int 或 unsigned int 类型 如果任何操作数的类型为更大 则转换为更大的类型比整数 积分促销 是旧的C90术
  • 如何在单击 DatagridView 中的另一个复选框列时禁用复选框列

    我有两个 ckecbox 错误和启用 如下所示 如果我取消选中 启用 复选框 相应的 错误 复选框将变为灰色 我尝试了如下但没有启用或禁用属性 void dgRulesMaster CellContentClick object sende
  • 什么更快?

    如果我们有以下 2 个 C 代码片段可以完成相同的任务 int a b somenumber while b gt 0 a b 3 b 3 or int b somenumber while b gt 0 int a b 3 b 3 我对计
  • Linq 选择行,其中日期在当月

    我需要获取当月的数据 一直无法找到有效的解决方案 这是我的代码 它为我提供了所需的数据 但我获取的是整整一个月前的数据 而不是当前月份的数据 我选择了两次日期 限制 row gt DateTime Today Addmonths 1 有任何
  • cudaMalloc使用向量>进行管理 > C++ - NVIDIA CUDA

    我正在通过 NVIDIA GeForce GT 650M GPU 为我创建的模拟实现多线程 为了确保一切正常工作 我创建了一些辅助代码来测试一切是否正常 在某一时刻 我需要更新变量向量 它们都可以单独更新 这是它的要点 device int
  • static_assert 有什么作用,你会用它做什么?

    你能举个例子吗static assert C 11 会优雅地解决手头的问题吗 我熟悉运行时assert 我应该选择什么时候static assert 超过常规assert 另外 在boost有一种东西叫做BOOST STATIC ASSER
  • 如何反转无符号整数的 4 个字节? [复制]

    这个问题在这里已经有答案了 我试图通过使用 和 以及按位 AND 和 OR 和 来反转无符号整数 但不知道如何执行此操作 我已经拥有的 int main int argc char argv unsigned int getal scanf
  • 使用 Elmah 进行异常处理

    我用 Elmah 记录异常 想知道我使用的技术是否是好的设计 现在 我捕获并重新抛出各种类和方法中发生的异常 并将它们记录到程序的主 try catch 块中的 Elmah 主程序 try Some code that fires off
  • 从文本文件中读取行并存储到数组中

    如何从文本文件中读取行并将其存储到数组中 例如 我有一个包含 45 行不同行的文本文件 我的尝试 int main int a 45 ifstream myfile enroll assg txt if myfile cout lt lt
  • 将 TableCell 文本转换为超链接

    我正在将 sql 查询中的数据提取到页面后面的 cs 代码中的 asp 表中 TableCell tCell1 new TableCell tCell1 Text myDataRow tid ToString 我想将其转换为超链接 我怎样才
  • C# 以非管理员权限运行进程

    我启动了一个有关管理员权限的流程 psi Verb runas process StartInfo psi process Start 但现在这个过程必须启动另一个应用程序 但需要非管理员权限 应用程序适用于非管理员权限 我怎样才能做到这一
  • 在c#中搜索支持rar格式的压缩库

    我想在我的应用程序中添加功能来解压缩 并可选择压缩 各种格式的文件 我有支持 zip gzip 7zip 和 bzip2 的库 但还是没有找到支持rar的库 我知道 rar 是商业的 但也许有一些 net 库可用于解压缩 rar s 最好是

随机推荐