ASP.NET MVC获取用户变量

时间:2022-12-04 18:50:08

Just getting started using MVC in ASP.NET, I'm going to have it so users must login to use certain features. Now I have a User controller that stores users in a table and another controller that adds data to another table. Once the user is logged in, how would I get their id from the user table from within the add controller in order to add their id to that table?

刚刚开始在ASP.NET中使用MVC,我将拥有它,因此用户必须登录才能使用某些功能。现在我有一个用户控制器将用户存储在一个表中,另一个控制器将数据添加到另一个表中。一旦用户登录,我如何从添加控制器中的用户表中获取他们的id,以便将他们的id添加到该表?

1 个解决方案

#1


I think that to solve your problem from the top down you might want to look into ASP.NET MVC Authentication instead of implementing something like this yourself. That said if you have a great reason for continuing down the path you're taking then I have some suggestions.

我认为,为了从上到下解决您的问题,您可能希望查看ASP.NET MVC身份验证,而不是自己实现这样的事情。那说如果你有充分的理由继续沿着你正在走的道路走,那我就有了一些建议。

Firstly you may wish to consider using the repository pattern to add/remove/get data to and from your database. Any controller can implement any repository it likes so your add controller can just implement the user repository to get the user.

首先,您可能希望考虑使用存储库模式向数据库添加/删除/获取数据。任何控制器都可以实现它喜欢的任何存储库,这样你的添加控制器就可以实现用户存储库来获取用户。

Also, remember that in ASP.NET MVC you can use session variables. If you need to know which user is doing what, then just store it in the session and retrieve it from there.

另外,请记住,在ASP.NET MVC中,您可以使用会话变量。如果您需要知道哪个用户在做什么,那么只需将其存储在会话中并从那里检索它。

#1


I think that to solve your problem from the top down you might want to look into ASP.NET MVC Authentication instead of implementing something like this yourself. That said if you have a great reason for continuing down the path you're taking then I have some suggestions.

我认为,为了从上到下解决您的问题,您可能希望查看ASP.NET MVC身份验证,而不是自己实现这样的事情。那说如果你有充分的理由继续沿着你正在走的道路走,那我就有了一些建议。

Firstly you may wish to consider using the repository pattern to add/remove/get data to and from your database. Any controller can implement any repository it likes so your add controller can just implement the user repository to get the user.

首先,您可能希望考虑使用存储库模式向数据库添加/删除/获取数据。任何控制器都可以实现它喜欢的任何存储库,这样你的添加控制器就可以实现用户存储库来获取用户。

Also, remember that in ASP.NET MVC you can use session variables. If you need to know which user is doing what, then just store it in the session and retrieve it from there.

另外,请记住,在ASP.NET MVC中,您可以使用会话变量。如果您需要知道哪个用户在做什么,那么只需将其存储在会话中并从那里检索它。