ASP.NET MVC:保存状态??使用会话?

时间:2009-12-03 15:59:50

标签: asp.net-mvc

我想知道是否有人可以提供帮助,我希望在当前页面上为当前用户全局保存变量,我认为Sessions在mvc中不好?

我应该举例说明我在做什么。基本上我有一个控制器,它进入(动作=索引),我检查

Request.UrlReferrer

如果它包含一个值,意味着它来自另一个地方,例如谷歌。然后我将信息写入日志。现在在控制器的这个阶段一切都很好。

但是稍后在我的页面中我想回忆一下控制器中的一个方法(使用jquery和ajax)来处理更多的跟踪,但记住我仍然在同一页面中,我使用

 Request.UrlReferrer

但是在这个阶段它总是会成为页面的名称,因为引用者是发起ajax调用和“NOT”谷歌的页面。好的,似乎我需要将值或UrlReferrer保存到全局变量/每个用户,这样当我重新进入我的控制器时,我可以检查这个SAVED变量而不是Request.UrlReferrer。

有谁知道最简单的方法吗?

这是我的页面的一个例子

public ActionResult Index()
    {
        // Process tracking - Initial entry
        string ip = Request.UserHostAddress.ToString();
        string referrer = null;

        if (Request.UrlReferrer !=null)
            referrer = Request.UrlReferrer.ToString();

        // WRITE THE LOGS HERE!!!!

        return View();
    }

    public ActionResult ProcessTracking()
    {
        // Reprocess tracking
        // BUt can't use Request.UrlReferrer as it returns my calling page and not google
        // for example




        //string ip = Request.UserHostAddress.ToString();
        //string referrer = null;

        //if (Request.UrlReferrer != null)
        //    referrer = Request.UrlReferrer.ToString();

        //return View();
    } 

2 个答案:

答案 0 :(得分:4)

您应该将值存储在TempData中。 TempData的全部目的是在控制器调用之间保持信息。从MVC 2 Beta开始,该值将保持不变,直至被读取。

public ActionResult Index()
{        
// Process tracking - Initial entry        
string ip = Request.UserHostAddress.ToString();        
string referrer = null;        
if (Request.UrlReferrer !=null)            
referrer = Request.UrlReferrer.ToString(); 
TempData["referrer"] = referrer;   
// WRITE THE LOGS HERE!!!!        
return View();    
}    

public ActionResult ProcessTracking()    
{        
// Reprocess tracking        
// BUt can't use Request.UrlReferrer as it returns my calling page and not google        
// for example        
string ip = Request.UserHostAddress.ToString();        
string referrer = TempData["referrer"];        
//continue processing here   
return View();    
}

答案 1 :(得分:0)

可以使用会话包来存储Request.UrlReferrer的第一个值。但是在WebForms中,请确保在会话变量未使用时删除它。这种持久性的另一个选择可以是cookie或MVC 1.0中的ASP.NET MVC TempData包,只能在重定向到另一个页面之前使用,而MVC 2.0 Beta TempData只有在读取时(或会话到期时)才会被清除

Lucas Oleiro