填充模型并在应用程序的任何位置访问它

Populate a model and access it anywhere on the app

我对 Razor 页面还很陌生 Asp.Net MVC Razor 页面, 我创建了一个包含用户字段的模型,并希望在我登录后用数据填充它,并通过调用该模型而不是进行另一个数据库调用来访问其他页面中的相同数据

这是我目前的代码

型号:

 public class Utilizador
{
    [Key]
    public int id { get; set; }

    [Required, MaxLength(100)]
    public string username { get; set; }

    [Required, MaxLength(100)]
    public string email { get; set; }

    [Required, MaxLength(100)]
    public string password { get; set; }

   
}

然后我给 Program.cs

添加了一个单例
builder.Services.AddSingleton<Utilizador>();

你可以用EF Core试试,官方文档:

https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/page?view=aspnetcore-6.0&tabs=visual-studio

https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/sql?view=aspnetcore-6.0&tabs=visual-studio

你可以在第一次登录验证的时候把你的数据存到Session或者Cache里面,以后可以直接从Session中调用数据,不需要再调用数据库

我的测试码:

Utilizador.cs:

public class Utilizador
{
    public int id { get; set; }
    public string username { get; set; }
    public string test { get; set; }     
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddScoped<Utilizador>();
    services.AddSession();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // other middleware
    app.UseSession();
    // other middleware
}

Test1.cshtml.cs:

public class Test1Model : PageModel
{
    private readonly Utilizador _Utilizador;

    private Utilizador model { get; set; }

    public Utilizador getValue { get; set; }

    public Test1Model(Utilizador Utilizador)
    {
        _Utilizador=Utilizador;
    }
    public async Task<IActionResult> OnGetAsync(int id)
    {
        if (id == 1)
        {
            _Utilizador.username = "MyTest";
            _Utilizador.test = "Success";
        }
        else 
        {
            _Utilizador.username = "MyTest";
            _Utilizador.test = "Fail";
        }
        model = _Utilizador;

        HttpContext.Session.Set<Utilizador>(id.ToString(),model);

        getValue=HttpContext.Session.Get<Utilizador>(id.ToString());

        return Page();   
      }
}

直接从对应页面获取数据:

Test1.cshtml:

@page
@model CacheTest.Pages.TestPage.Test1Model

<div>@Model.getValue.username</div>
<div>@Model.getValue.test</div>

Test2.cshtml.cs:

public class Test2Model : PageModel
{
    public Utilizador getValue { get; set; }
    public void OnGet(int id)
    {
        getValue = HttpContext.Session.Get<Utilizador>(id.ToString());
    }        
}

Test2.cshtml:

@page
@model CacheTest.Pages.TestPage.Test2Model

<div>@Model.getValue.username</div>
<div>@Model.getValue.test</div>

测试结果

Test1中,先存后读:

直接读取Test2中session存储的数据: