在MVC中使用Json时清除会话值

时间:2019-01-16 05:36:24

标签: json asp.net-mvc

我正在创建一个模式弹出窗口来创建事件,并且我只允许登录用户查看该页面,保存事件和获取事件都使用json,但是注销后返回时,会话值仍然存在并且所有操作都将执行,直到我不刷新页面为止,我希望不执行任何操作,并且注销时应清除会话值

    public ActionResult Index()
    {

        if(Session["UserID"]==null)
        {
            return RedirectToAction("Index2","Login");
        }
        else
        {
            TempData["usersession"] = Session["UserID"].ToString();
        }
            return View();


    }

<label id="session">@TempData["usersession"]</label>

  //Javascript and Json



$(document).ready(function () {
            username = $('#session').text();
});
 function SaveEvent(data) {
                alert(username);
                    $.ajax({
                        type: "POST",
                        url: '/home/SaveEvent',
                        data: data,
                        success: function (data) {
                            if (data.status) {
                                //Refresh the calendar
                                fetchEvent();
                                $('#myModalSave').modal('hide');
                                //alert(username);
                            }
                        },
                        error: function () {
                            alert('failed');
                        }
                    });

当我尝试在用户名上单击时提醒用户名时,它仍显示会话值

1 个答案:

答案 0 :(得分:0)

您尝试过这个吗?

 Session.Abandon(); // The Abandon method destroys all the objects stored in a Session object and releases their resources. 

    Session.Remove("YourItem"); //just removes current values

    Session.Clear();// just removes all values

https://stackoverflow.com/a/5330288/7262120

public class VerifyUserAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var user = filterContext.HttpContext.Session["UserID"];
        if (user == null)
            filterContext.Result = new RedirectResult(string.Format("/User/Login?targetUrl={0}",filterContext.HttpContext.Request.Url.AbsolutePath));
    }
}
[VerifyUserAttribute]
 public ActionResult Index()
    {

        if(Session["UserID"]==null)
        {
            return RedirectToAction("Index2","Login");
        }
        else
        {
            TempData["usersession"] = Session["UserID"].ToString();
        }
            return View();


}