在_ViewStart.cshtml中定义全局变量

问题描述

我们正在使用.NET Core 3.1。我们想在_ViewStart.cshtml中定义一个全局变量(当前用户的电子邮件),以便所有其他视图都可以访问它。通过这样做,我们旨在避免重复的代码

以下代码

@using System.Security.Claims
Your email: @User.FindFirstValue(MyClaimTypes.Email)

可以替换为:

Your email: @email

我尝试像这样在_ViewStart.cshtml中定义电子邮件

@{
    Layout = "_MyLayout";
    string email = "[email protected]";
}

,然后在Index.cshtml中访问它:

Your email: @email

但是它说

名称“ email”在当前上下文中不存在。

我们如何从所有其他视图访问_ViewStart.cshtml中定义的变量?

解决方法

_ViewImports.cshtml中,您可以像这样注入变量:

@using MyApp.AspNetCore
@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers

@{ 
    string UserEmail = "[email protected]";
}
@inject string UserEmail;

Index.cshtml中,您可以通过其名称进行引用:

<span>Hello @UserEmail </span>