You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

要求用ViewBag替换Session变量,但其生命周期有限,是否更优?

Is ViewBag a Better Choice Than Session Here?

Great question—let’s unpack this scenario step by step to clarify whether ViewBag is the right fit.

First, let’s recap the context: Your original code uses Session["House"] to set a default value in OnActionExecuting, but you’re being asked to switch to ViewBag.House because OnActionExecuting runs per request, and Session’s cross-request lifecycle is unnecessary here.

Your Core Concern Addressed

You’re right that ViewBag is limited to the current request lifecycle—it doesn’t persist across redirects or subsequent requests. But let’s break down when that’s a feature, not a bug:

  1. What’s the actual purpose of the House value?

    • If this value only needs to be accessed within the current request (e.g., by the upcoming Action method and its corresponding View), ViewBag is perfect. It’s lightweight, doesn’t clog up server-side Session storage, and avoids unintended state leakage between requests.
    • If you needed this value to persist across multiple user requests (e.g., remembering a user’s selected House for their entire session), then Session would be necessary. But based on the requirement’s reasoning, this isn’t the case here—OnActionExecuting runs every request, so setting a default per request makes sense with ViewBag.
  2. ViewBag does work between Controller and View
    Your concern about "ViewBag not passing between View and Controller" is only true for separate requests. Within the same request, any value you set on ViewBag in OnActionExecuting will be available to the Action method and the View it renders.

Modified Code Example

Here’s how you’d adjust your base controller code to use ViewBag, aligned with the original logic (setting a default if no value exists):

protected override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    // Set default House value if not already present in the current request
    if (ViewBag.House == null)
        ViewBag.House = Enums.Houses.Black;
}

Final Verdict

If the House value is only needed for the current request’s Action/View flow, ViewBag is absolutely the better choice. It avoids the overhead of Session (which persists across requests) and keeps your request-scoped state clean. If you ever need to persist this value across requests, you can always switch back to Session (or another state management tool like TempData for redirects).

内容的提问来源于stack exchange,提问作者kfwbird

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:18:30