gpt4 book ai didi

c# - Extended Controller 构造函数没有 User 的实例

转载 作者:行者123 更新时间:2023-11-30 17:27:59 25 4
gpt4 key购买 nike

我有一个从 Controller 扩展而来的基本 Controller ,该类工作正常,但我认为我使用了很多次代码来从数据库中获取当前用户。所以我想我应该创建一个构造函数并将我在每个函数中使用的代码移到那里。基本上,我想做的是为我的 Controller 中的任何方法准备好参数。

所以,这就是我现在拥有的(并且工作正常):

public class UsersController : Controller
{
private DBContext db = new DBContext();

public ActionResult Info()
{
User user = db.Users.Where(m => m.username.Equals(User.Identity.Name)).FirstOrDefault();
return View(user);
}

public ActionResult Edit(int? id){
User user = db.Users.Where(m => m.username.Equals(User.Identity.Name)).FirstOrDefault();
if(user.id == id){
return View(user);
}
}
}

但我的想法是创建这样的东西:

public class UsersController : Controller
{
private DBContext db = new DBContext();
private User _user;

public UsersController()
{
_user = db.Users.Where(m => m.username.Equals(User.Identity.Name)).FirstOrDefault();
}

public ActionResult Info()
{
return View(_user);
}

public ActionResult Edit(int? id){
if(_user.id == id){
return View(_user);
}
}
}

当我进行这些更改时,出现以下错误:

Server Error in '/' Application. Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

我试过调试,发现问题是我的 Usernull 当构造函数被调用,所以我猜,一些其他语言可以在添加自己的自定义之前或之后调用父构造函数,例如这样的事情:

public function __Construct($x){
$this->x = $x
parent::__construct();
}

public function __Construct($x){
parent::__construct();
$this->x = $x
}

我尝试在我的程序中使用 base 做同样的事情,但似乎没有任何效果,而且它总是导致我出现其他性质的错误。我什至不确定这是正确的方法,因为我只需要在构造函数中创建我的 User (Identity)

最佳答案

听起来好像找不到用户,可能是因为在调用 Controller 的构造函数时用户身份未填充到线程的主体上。

我的建议是避免在构造函数中提取用户数据,而是在需要时获取。为避免重复代码,您可以编写 protected 或私有(private)方法(不是操作方法)来获取它:

public class UsersController : Controller
{
private DBContext db = new DBContext();

private User GetCurrentUser()
{
return db.Users.Where(m => m.username.Equals(User.Identity.Name)).FirstOrDefault();
}

public ActionResult Info()
{
var user = GetCurrentUser();
return View(user);
}

public ActionResult Edit(int? id){
var user = GetCurrentUser();
if(user.id == id){
return View(user);
}
}
}

关于c# - Extended Controller 构造函数没有 User 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53890668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com