在Asp.Net使用的Cookie的mvc 4 [英] Using Cookie in Asp.Net Mvc 4

查看:140
本文介绍了在Asp.Net使用的Cookie的mvc 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Asp.Net MVC4 的Web应用程序,我想使用饼干作为用户的登录和注销。所以,我的行为如下:

I have web application in Asp.Net MVC4 and I want to use cookie for user's login and logout. So my actions as follows:

登录操作

    [HttpPost]
    public ActionResult Login(string username, string pass)
    {
        if (ModelState.IsValid)
        {
            var newUser = _userRepository.GetUserByNameAndPassword(username, pass);
            if (newUser != null)
            {
                var json = JsonConvert.SerializeObject(newUser);

                var userCookie = new HttpCookie("user", json);
                userCookie.Expires.AddDays(365);
                HttpContext.Response.Cookies.Add(userCookie);

                return RedirectToActionPermanent("Index");
            }
        }
        return View("UserLog");
    }

注销操作

    public ActionResult UserOut()
    {
        if (Request.Cookies["user"] != null)
        {
            var user = new HttpCookie("user")
                {
                    Expires = DateTime.Now.AddDays(-1),
                    Value = null
                };
            Response.Cookies.Add(user);
        }
        return RedirectToActionPermanent("UserLog");
    }

和我使用这个cookie在_Loyout如下:

And I use this cookie in _Loyout as follow:

@using EShop.Core
@using Newtonsoft.Json
@{
   var userInCookie = Request.Cookies["user"];
}
...
  @if (userInCookie != null && userInCookie.Value)
  {
        <li><a href="#">Salam</a></li>
        <li><a href="@Url.Action("UserOut", "Home")">Cıxış</a></li>
  }
  else
  {
        <li><a href="@Url.Action("UserLog", "Home")">Giriş</a></li>
  }

不过,当我的点击的* UserOut *动作这个动作发生的第一次,但后来它不工作。我把断点寻找过程,但它获得的用户日志的动作不的 UserOut 的。
我的问题是,当我使用的cookie的错误的方式?什么是使用cookie的一个最好的办法的 Asp.Net Mvc4 的这种情况?

But When I click *UserOut* action this action happen first time, but then it doesn't work. I put breakpoint for looking process but it get UserLog action doesn't UserOut. My question is that where I use wrong way of cookie? What is a best way using cookie in Asp.Net Mvc4 for this scenario ?

推荐答案

尝试使用 Response.SetCookie(),因为 Response.Cookie.Add ()可导致添加多个饼干,而的setcookie 将更新现有的cookie。

Try using Response.SetCookie(), because Response.Cookie.Add() can cause multiple cookies to be added, whereas SetCookie will update an existing cookie.

这篇关于在Asp.Net使用的Cookie的mvc 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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