加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 在MVC 3中写入只读会话

发布时间:2020-12-15 18:53:22 所属栏目:asp.Net 来源:网络整理
导读:我遇到了一个好奇的ASP会话的行为。你可以强制控制器超出用户的会话 – 我想能够这样做,使多个请求可以同时执行,并使用会话使它们连续执行。 禁用会话状态按预期工作: [SessionState(SessionStateBehavior.Disabled)]public class SampleController : Con
我遇到了一个好奇的ASP会话的行为。你可以强制控制器超出用户的会话 – 我想能够这样做,使多个请求可以同时执行,并使用会话使它们连续执行。

禁用会话状态按预期工作:

[SessionState(SessionStateBehavior.Disabled)]
public class SampleController : Controller
{
    public ActionResult Test() 
    {
        // Access to the session should be denied
        object test = Session["test"];
        return Content(test);
    }
}

到?/ Sample / Test会抛出一个System.Web.HttpException异常。
但是,只读会话似乎有点奇怪:

[SessionState(SessionStateBehavior.ReadOnly)]
public class SampleController : Controller
{
    public ActionResult Test() 
    {
        // Read from the session should be fine
        object test = Session["test"];
        return Content(test);
    }

    public ActionResult SetTest(string value) 
    {
        // Write to the session should fail 
        Session["test"] = value;

        // Read it back from the session
        object test = Session["test"];
        return Content(test);
    }
}

所以现在我期望?/ Sample / Test工作,而且它。奇怪的是,集合也是:我去?/ Sample / SetTest?value = foo,它不抛出异常,实际上它返回“foo”。如果我调用?/ Sample / SetTest?value = bar,然后?/ Sample / Test我得到“bar”,表示会话已经写入。

所以在SessionStateBehavior.ReadOnly我已经成功写入会话并读取我的值。

我认为这可能是由于三件事之一:

>在MVC 3 [SessionState(SessionStateBehavior.ReadOnly)]被打破/忽略。
>当会话被写入并变为可写时,[SessionState]被覆盖。
> SessionStateBehavior.ReadOnly实际上表示某种脏/乐观访问。

任何人都可以确认?

我怀疑最后一个是真的,基于custom session provider documentation – 如果这是怎么实现的工作?写入“只读”会话是否会产生并发错误(即最后写入胜利),还是会导致会话损坏和异常中断?

更新

看起来这是设计(从Microsoft’s docs):

Note that even if the EnableSessionState attribute is marked as
ReadOnly,other ASP.NET pages in the same application might be able to
write to the session store,so a request for read-only session data
from the store might still end up waiting for locked data to be freed.

看起来像上面的第二个选项是它实际上做的 – 会话被锁定和模式更改为可写。

解决方法

?/ Sample / SetTest?value = foo

是的,它不会抛出任何错误,但它也没有持续会话在请求结束。通过设计,您写入会话的任何事情都会在请求生命周期的最后更新(只有会话是可写的)。

在我的测试?/ Sample / Test什么都不返回。

我认为他们应该在这里失败,当会议是readonly。

顺便说一下,你的样品需要重写

string test = (string)this.Session["test"];

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读