要求用ViewBag替换Session变量,但其生命周期有限,是否更优?
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:
What’s the actual purpose of the
Housevalue?- 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—
OnActionExecutingruns every request, so setting a default per request makes sense with ViewBag.
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 onViewBaginOnActionExecutingwill 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

