gpt4 book ai didi

c# - HttpContextBase.Session 和 HttpContext.Current.Session 在 IRouteConstraint MVC4 上都是空的

转载 作者:太空宇宙 更新时间:2023-11-03 10:57:46 27 4
gpt4 key购买 nike

我无法在我的自定义 RootConstraint 类上访问 Session,它已设置为 null。我已经搜索过但找不到解决方案。

public class AdminRootConstraint : IRouteConstraint
{
public bool Match
(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection
)
{
if ((string) values["controller"] == "Login")
return true;

return HttpContext.Current.Session != null && (bool)HttpContext.Current.Session["IsAuthorized"];
}
}

编辑

这是 httpContext 参数在即时窗口中的样子。可能会给出一个想法。

httpContext
{System.Web.HttpContextWrapper}
[System.Web.HttpContextWrapper]: {System.Web.HttpContextWrapper}
AllErrors: null
AllowAsyncDuringSyncStages: false
Application: {System.Web.HttpApplicationStateWrapper}
ApplicationInstance: {ASP.global_asax}
AsyncPreloadMode: None
Cache: {System.Web.Caching.Cache}
CurrentHandler: null
CurrentNotification: ResolveRequestCache
Error: null
Handler: null
IsCustomErrorEnabled: false
IsDebuggingEnabled: true
IsPostNotification: true
IsWebSocketRequest: false
IsWebSocketRequestUpgrading: false
Items: Count = 0x00000000
PageInstrumentation: {System.Web.Instrumentation.PageInstrumentationService}
PreviousHandler: null
Profile: null
Request: {System.Web.HttpRequestWrapper}
Response: {System.Web.HttpResponseWrapper}
Server: {System.Web.HttpServerUtilityWrapper}
Session: null
SkipAuthorization: false
ThreadAbortOnTimeout: true
Timestamp: {14.09.2013 16:52:53}
Trace: {System.Web.TraceContext}
User: {System.Security.Principal.WindowsPrincipal}
WebSocketNegotiatedProtocol: null
WebSocketRequestedProtocols: null

编辑2

我在同一区域的操作中使用 RedirectToAction 方法,并且 Match 方法在我跟踪时执行了两次。第一次执行时,routeDirection参数设置为System.Web.Routing.RouteDirection.UrlGeneration,此时Session不为空。但是当第二次执行时,routeDirection 参数设置为 System.Web.Routing.RouteDirection.IncomingRequest 并且 session 为空。为什么?

最佳答案

第一次调用 Match 是因为 MVC 正在构建它将导航用户浏览器的 URL(通过发送 HTTP 302)。这一次你有 session 只是因为它在那一刻存在。

第二次调用 Match 是在请求​​到达浏览器时。这次 session 不存在,因为路由逻辑是在 session 加载之前执行的。例如。路由可能会呈现根本不需要 session 的页面。

总而言之, session 在 IRouteConstraint 中不可访问,不应使用。

关于c# - HttpContextBase.Session 和 HttpContext.Current.Session 在 IRouteConstraint MVC4 上都是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18801923/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com