asp.net-core - Razor Pages,如何将路线值添加到导航链接?
问题描述
我尝试将我的 Employee 模型注入 _ViewImports.cshtml,但它不起作用,因为它会引发依赖注入错误。我有访问模型的 using 语句。
_ViewImports.cshtml
@using NavraePortal.DataLayer.Models
@namespace NavraePortal.WebApp.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@inject Employee Employee
我正在尝试传递登录者的 ID。我知道我可以获得 Identity 值,但我想使用自己的值。
所以在 _Layout.cshtml 我想将 Employee.EmployeeId 传递到 asp-route-id 中,如下所示:
<li class="nav-item">
<a class="nav-link text-dark" asp-page="/Details" asp-route-id="@Employee.EmployeeId">Profile</a>
</li>
有什么技巧可以得到这个。谷歌搜索Inject Id into navigation parameter
并没有向我展示太多。
#------------------------------------------------ --------------------#
#编辑#
所以我在更改用户电子邮件地址时遇到了一个问题。电子邮件在我的数据库中的两个位置,一个在 Microsoft Identity 中,另一个在我的数据库中。发生此问题是因为我在更改 Identity.User.Name 和我的 Db.Email 后进行了比较。这些电子邮件不再匹配,因此我的应用程序抛出空异常,因为它无法找到用户(电子邮件不再匹配)。
费仍然帮助我找到了更好的解决方案。我将 UserManager 和我的 Interface 类注入到 _Layout.cshtml 文件中,并使用一个变量来获取 EmployeeId。由于这永远不会改变,因此它是一种更好的检查方法,并且仍然为我提供了我正在寻找的相同功能。再次感谢费帮助我得出这个答案!
解决方案
我正在尝试传递登录者的 ID。我知道我可以获得 Identity 值,但我想使用自己的值。
如果您想实现自定义服务来获取EmployeeId
经过身份验证的员工,然后将该自定义服务注入_ViewImports.cshtml
文件中,您可以参考以下代码片段。
public class Employee
{
public string EmployeeId { get; set; }
private readonly IHttpContextAccessor _httpContextAccessor;
//if you need other instance of service(s), please make use you register and inject it successfully
public Employee(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
if (_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
{
var name = _httpContextAccessor.HttpContext.User.Identity.Name;
//in actual scenario, you may need to call other service to get Id of current user
//for testing purpose, I am using "dummy" EmployeeID
EmployeeId = "d3eba67d-cdb1-4954-ba9f-9da223df8a12";
}
else
{
//code logic here
//...
//assign other value to EmployeeId
EmployeeId = "IdForNonAuthenticatedEmployee";
}
}
}
在 Startup.cs 中注册服务
services.AddHttpContextAccessor();
services.AddScoped<Employee>();
测试结果
推荐阅读
- javascript - 如何安装 npm peerDependencies 以删除警告
- nginx - Nginx 批量 URL 重定向
- webgl - 通过生成 MipMap 对 Webgl2 R32F 纹理中的值求和
- javascript - json.stringify(obj) 错误 obj 未定义
- php - Wordpress 帖子丢失但在数据库中仍然可见
- javascript - 引导选择器不显示选项
- python - 通过python正则表达式忽略ip地址的第一个八位字节中的这两个数字(以127或0开头)
- c# - Unity:拥有植被/草地的最有效方式(移动性能)?
- ajax - Ajax 用表单提交图片 - 传递 FormData - 触发提交
- javascript - Chrome/Safari/Firefox JavaScript 自动将日期格式更改为 DD-MM-YYYY 格式