【问题标题】:Keep object state between OnGet and OnPost在 OnGet 和 OnPost 之间保持对象状态
【发布时间】:2020-08-31 09:16:33
【问题描述】:

我在我的Startup 类中注册了一项服务,在我的页面的OnGet() 方法之一中初始化我的UserService 的属性,然后调用OnPost(),使我的属性丢失。我做错了什么?解决办法是什么?

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  //...
  services.AddScoped<IUserService, UserService>();
}

我的 UserService 类

public class UserService : IUserService
{
  // ...
  private ApplicationUser _appUser;
  public void Initalize(ClaimsPrincipal claim)
  {
    var curretUserId = claim.FindFirstValue(ClaimTypes.NameIdentifier);
    _appUser =  _userManager.FindByIdAsync(curretUserId).Result;
  }
}

我的主页的一个后端

[Authorize]
public class CreateModel : PageModel
{
  // ....
  private readonly IUserService _userService;
  public CreateModel( // ... dependencies,
                     IUserService userService)
  {
    _userService = userService;
  }

  public async Task<IActionResult> OnGetAsync(string id)
  {
    // ...
    _userService.Initalize(User);
    // everything are good here, _appUser is initalized and I have all my properties are initialized
  }
  public async Task<IActionResult> OnPostAsync()
  {
    // _userService._appUser is NULL here. Why?
  }
}

【问题讨论】:

  • 嗨。用第二种方法更新了我的答案。

标签: c# asp.net-core razor dependency-injection asp.net-core-mvc


【解决方案1】:

问题是每次请求都会重新创建您的 UserService。

更新

因为我的第一个答案由于某种未知原因没有解决 OPs 问题,所以这里是第二个建议。

将此添加到PageModel 类(如果更合适,可以是 int 类型)

[BindProperty]
public string SelectedUserId { get; set; }

像这样更改 get- 和 post 方法

public async Task<IActionResult> OnGetAsync(string id)
{
  ...
  SelectedUserId = ... some value
  ...
}

public async Task<IActionResult> OnPostAsync()
{
   ... use SelectedUserId to get user to work with
   
   ...
}

这里的线索是将表单内的请求之间的 SelectedUserId 保存为隐藏。

如果这还不够,来自 object 的多个属性可能会被序列化为表单中的多个隐藏,并在 PageModel 类中反序列化。

为了达到最高级别,对象可以实现 ToString,将对象字符串存储在一个隐藏的表单中,并在发布请求时反序列化对象。

很遗憾,我们在问题中没有任何可用的标记,因此我省略了这部分。

【讨论】:

  • 我的 UserService 中有多个方法和多个属性,但没有包含我类的每一行代码。这不是我的问题的解决方案。
  • 至少你已经解释了为什么当前的解决方案不起作用:-)
猜你喜欢
  • 2019-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多