何时在 ASP.Net MVC 中使用 TempData 与 Session [英] When to use TempData vs Session in ASP.Net MVC

查看:21
本文介绍了何时在 ASP.Net MVC 中使用 TempData 与 Session的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试掌握 MVC 框架的窍门,所以请耐心等待.

I am trying to get the hang of MVC framework so bear with me.

现在,我使用会话存储的唯一目的是存储当前登录的用户.我的网站很简单.对于此示例,请考虑三个域对象:人员、会议和文件.用户可以登录并查看会议的仅限会员"个人资料,也可以向其中添加文件,或者在未登录的情况下查看会议的公开个人资料".

Right now, the only thing I'm using the session store for is storing the current logged in user. My website is simple. For this example, consider three domain objects, Person, Meeting, and File. Users can log in and view a "members only" profile of a meeting and can add files to it, or view a meeting's public "profile" if they aren't logged in.

因此,从会议的私人资料中,使用登录用户,我有一个添加文件"链接.此链接路由到 FileContoller.Add(int meetingId).从这个操作中,我得到了用户想要使用会议 id 添加文件的会议,但是在表单发布后,我仍然需要知道用户正在向哪个会议添加文件.这就是我的问题所在,我应该通过 TempData 传递当前正在与之交互"的会议,还是将其添加到 Session 存储中?

So, from the meeting's private profile, with a logged in user, I have a "add files" link. This link routes to FileContoller.Add(int meetingId). From this action, I get the meeting the user want to add files to using the meeting id, but after the form is posted, I still need to know which meeting the user is adding files to. That's where my question lies, should I pass the "currently interacting with" meeting through TempData, or add it to the Session store?

这是我目前设置添加操作的方式,但它不起作用:

This is how I currently have the Add action setup, but it's not working:

    public ActionResult Add(int meetingId)
    {
        try
        {
            var meeting = _meetingsRepository.GetById(meetingId);
            ViewData.Model = meeting;
            TempData[TempDataKeys.CurrentMeeting] = meeting; /* add to tempdata here */
        }
        catch (Exception)
        {
            TempData[TempDataKeys.ErrorMessage] = "Unable to add files to this meeting.";
            return RedirectToRoute("MeetingsIndex");
        }

        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Add(FormCollection form)
    {
        var member = Session[SessionStateKeys.Member] as Member;
        var meeting = TempData[TempDataKeys.CurrentMeeting] as Meeting; /* meeting ends up null here */

        if (member == null)
        {
            TempData[TempDataKeys.ErrorMessage] = "You must be logged in to add files to an meeting.";
            return RedirectToRoute("LoginPage");
        }

        if (meeting == null) 
        {
            TempData[TempDataKeys.ErrorMessage] = "An error occurred. No meeting selected.";
            return RedirectToRoute("MeetingsIndex");
        }

            // add files to meeting

        TempData[TempDataKeys.Notification] = "Successfully added.";
        return RedirectToRoute("AddFiles", new {meetingId = meeting.MeetingId});
}


基于大多数答案,谁能提供任何示例来说明应在 TempData 与 Session 中存储哪种数据(消息除外)?

Based on most of the answers, can any one provide any examples on what kind of data (other than messages) should be stored in TempData vs Session?

推荐答案

TempData 是会话,所以它们并不完全不同.但是,区别很容易理解,因为 TempData 用于重定向,并且仅用于重定向.因此,当您在 TempData 中设置一些消息然后重定向时,您就正确地使用了 TempData.

TempData is session, so they're not entirely different. However, the distinction is easy to understand, because TempData is for redirects, and redirects only. So when you set some message in TempData and then redirect, you are using TempData correctly.

然而,将 Session 用于任何类型的安全都是极其危险的.会话和成员资格在 ASP.NET 中是完全分开的.您可以窃取"其他用户的会话,是的,人们确实以这种方式攻击网站.因此,如果您想根据用户是否登录来选择性地停止发布信息,请查看 IsAuthenticated,如果您想根据登录的用户类型有选择地显示信息,您可以使用 角色提供程序.由于 GET 可以缓存,唯一有选择地允许访问 GET 中的操作的方法是使用 AuthorizeAttribute.

However, using Session for any kind of security is extremely dangerous. Session and Membership are entirely separate in ASP.NET. You can "steal" sessions from other users, and yes, people do attack web sites this way. So if you want to selectively stop a post information based on whether a user is logged in, look at IsAuthenticated, and if you want to selectively show information based on what type of user is logged in, you use a Role provider. Because GETs can be cached, the only way to selectively allow access to an action in a GET is with AuthorizeAttribute.

更新 针对您编辑的问题:您已经有一个在问题中使用 TempData 的好例子,即在 POST 失败后返回一条简单的错误消息.就应该存储在Session中的内容而言(除了不多"),我只是将Session视为用户特定的缓存.与非用户特定的缓存一样,您不应将安全敏感信息放在那里.但这是一个放置查找相对昂贵的东西的好地方.例如,我们的 Site.Master 上显示了用户的全名.它存储在数据库中,我们不想为我们服务的每个页面都进行数据库查询.(我们的应用程序安装在一家公司中使用,因此用户的全名不被视为安全敏感".)因此,如果您将 Session 视为缓存,它会因用户拥有的 cookie 而有所不同,那么您将不会大错特错.

Update In response to your edited question: You already have a good example of using TempData in your question, namely, returning a simple error message after a failed POST. In terms of what should be stored in Session (beyond "not much"), I just think of Session as a user-specific cache. Like the non-user-specific Cache, you should not put security-sensitive information there. But it's a good place to stick stuff which is relatively expensive to look up. For example, our Site.Master has the user's full name displayed on it. That is stored in a database, and we don't want to do a database query for it for every page we serve. (An installation of our application is used in a single company, so a user's full name is not considered "security-sensitive.") So if you think of Session as a cache which varies by a cookie which the user has, you won't be far wrong.

这篇关于何时在 ASP.Net MVC 中使用 TempData 与 Session的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆