【问题标题】:Where to check for cookie in MVC3 app?在 MVC3 应用程序中在哪里检查 cookie?
【发布时间】:2012-02-04 11:06:11
【问题描述】:

我有一个 MVC3 Web 应用程序,它有效地“固定”到一个经典的 ASP 网站(即旧页面是经典的 asp,新页面是 ASP.Net MVC)。 该站点需要用户登录,因此为了保护新的 MVC 页面,我检查了一个 cookie 并使用 id 从经典 ASP 登录页面创建的数据库中检索会话数据。

因为用户可以在新旧页面之间切换,而且我没有在 2 个应用程序之间共享会话数据,所以我会在我的名为 LogIn 的操作方法中检查 cookie 并检索每个请求:

public PartialViewResult LogIn()
        {
            var cookieId = DecodeCookieId(System.Web.HttpContext.Current.Request.Cookies["cookiename"].Value);

            LoggedInViewModel viewModel = new LoggedInViewModel
            {
                Session = sessionRepository.Sessions.FirstOrDefault(s => s.GGAPSession_ID == cookieId)
            };
            return PartialView(viewModel);
        }

这会将数据传递给 ViewModel,它会在每个 MVC 页面的顶部显示登录的用户名,这就是为什么我认为这是进行检查的好地方。

当我尝试修改 LogIn() 以检查 cookie 并在未找到时重定向时出现问题:

public ActionResult LogIn()
{
   if (System.Web.HttpContext.Current.Request.Cookies["cookiename"] != null)
  {
     //  same method contents as above
  }
  else
  {
    return Redirect("http://localhost/index.asp");
  }
}

我得到一个“不允许子操作执行重定向操作”,我理解,但我该如何解决这个问题?我应该在其他地方进行 cookie 检查吗?我应该在哪里进行会话管理?

【问题讨论】:

  • 你的mvc站点和asp站点在同一个域下吗?
  • MVC站点是asp站点的子域

标签: c# asp.net-mvc cookies


【解决方案1】:

说明

对,你可以用HttpContext.Response.Redirect来解决这个问题。

样本

改变

return Redirect("http://localhost/index.asp");

HttpContext.Response.Redirect("http://localhost/index.asp");
return EmptyResult();

更多信息

【讨论】:

    【解决方案2】:

    我认为您可以在您的 mvc 站点中使用全局操作过滤器来执行此操作。这是《ASP.NET MVC in Action》一书中所述的一般原则。在

    中进行检索
    OnActionExecuting
    

    如果 cookie 存在。否则,

    filterContext.Result = new RedirectResult("http://localhost/index.asp")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      相关资源
      最近更新 更多