1

So when you make websites using Java you have something called a Session in which you can store any information you want basically for as long as that browser session is going on.

I'm fairly new with using ASP.NET MVC 3 and being able to pass around the right data at the right time is something that leaves me tied up quite often. For the most part I understand passing variables from views to controllers and back to other views.

But I was wondering if there's a way to make something that allowed to to let's say, grab a user's address from any view? I know there is User.Identity.Name built in and this is very handy for checking that a user is on their own page, etc. But is there any way to have a User object with custom information that is accessible anywhere?

I'm currently working on having a reputation system on my website (much like this website) where different amounts of reputation allow you to do different things. So in a lot of views I need to say "Hey, if the user has this reputation, let them see this feature." But this is extremely tedious if I have to pass in a user into every single view.

Any ideas?

4

2 に答える 2

1

カスタム クラス オブジェクトを Session のままにしておくことができます。セッションはリクエスト間で利用できます。

このようなクラスがあると仮定します

public class LoggedInUser
{
  public string DisplayName { set;get;}
  //Other relevant properties. relevant only not everything !
}

このようにセッションに保存できます

LoggedInUser objLoggedInUser=new LoggedInUser();
objLoggedInUser.DisplayName="Johnson";
Session["LoggedUser"]=objLoggedInUser;

これが必要な場所ならどこでも、このようにセッションから読み取ることができます

LoggedInUser objLoggedInUser;
if(LoggedInUser objLoggedInUser=!=null)
{
  objLoggedInUser=(LoggedInUser)Session["LoggedUser"];
  // Now you can access objLoggedInUser.DisplayName
}

この機能を関数にラップし、その関数を呼び出して、必要な場所でデータを取得します。

于 2012-04-17T03:27:27.587 に答える
1

HttpContext.Sessionを探していると思います。

セッションと ASP.NET MVC に関する詳細情報が必要な場合は、この記事を参照して、要求中にいつセッションが使用可能になるかについて理解を深めてください。

于 2012-04-17T03:19:55.887 に答える