Asp.net core Razor Pages,如何向导航链接添加路线值?
我已经尝试将我的员工模型注入到_ViewImports.cshtml中,但由于它抛出了依赖项注入错误,因此无法工作。我有用于访问模型的using语句 \u ViewImports.cshtmlAsp.net core Razor Pages,如何向导航链接添加路线值?,asp.net-core,razor,Asp.net Core,Razor,我已经尝试将我的员工模型注入到_ViewImports.cshtml中,但由于它抛出了依赖项注入错误,因此无法工作。我有用于访问模型的using语句 \u ViewImports.cshtml @using NavraePortal.DataLayer.Models @namespace NavraePortal.WebApp.Pages @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @inject Employee Employee
@using NavraePortal.DataLayer.Models
@namespace NavraePortal.WebApp.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@inject Employee Employee
我正在尝试传递登录者的ID。我知道我可以获得标识值,但我想使用我自己的值
因此,在_Layout.cshtml中,我希望将Employee.EmployeeId传递到asp路由id中,如下所示:
<li class="nav-item">
<a class="nav-link text-dark" asp-page="/Details" asp-route-id="@Employee.EmployeeId">Profile</a>
</li>
轮廓
有什么诀窍可以做到这一点吗。谷歌搜索在导航参数中插入Id
并没有显示太多信息
#---------------------------------------------------------------------#
#编辑#
因此,我在更改用户电子邮件地址时遇到了一个问题。电子邮件在我的数据库中有两个位置,一个在Microsoft Identity中,另一个在我的数据库中。更改Identity.User.Name后,我将其与我的Db.Email进行比较时,出现了此问题。这些电子邮件不再匹配,因此我的应用程序抛出了一个空异常,因为它找不到用户(电子邮件不再匹配)
Fei仍然帮助我找到了更好的解决方案。我将UserManager和我的接口类注入到_Layout.cshtml文件中,并使用一个变量来获取EmployeeId。由于这一点从未改变,因此这是一种更好的检查方法,并且仍然为我提供了我所寻找的相同功能。再次感谢费帮助我得到这个答案
我正在尝试传递登录者的ID。我知道我可以获得标识值,但我想使用我自己的值
如果您想实现一个定制服务来获取经过身份验证的员工的EmployeeId
,然后将该定制服务注入\u 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.addScope();
测试结果
谢谢,@Fei Han,这就是我要找的。对于其他人来说,您需要将您的客户上下文注入页面
@injectcontext.CustomContext CustomContext
请注意,我在测试更改电子邮件功能时遇到了使用此方法的问题。我在我原来的帖子中解释了更多。
services.AddHttpContextAccessor();
services.AddScoped<Employee>();