{"record":{"id":"4f2a9088b27992f4","repo":"JeffreySu/WeiXinMPSDK","slug":"httpcontext-request-null","errorCode":null,"errorMessage":"httpContext.Request 不能为null！","messagePattern":"httpContext\\.Request 不能为null！","errorType":"exception","errorClass":"WeixinNullReferenceException","httpStatus":null,"severity":"error","filePath":"src/Senparc.Weixin.AspNet/Utilities/HttpUtility/UrlUtility.cs","lineNumber":100,"sourceCode":"\n#if NET462\n\n            if (httpContext.Request.Url == null)\n            {\n                throw new WeixinNullReferenceException(\"httpContext.Request.Url 不能为null！\", httpContext.Request);\n            }\n\n            var returnUrl = httpContext.Request.Url.ToString();\n            var urlData = httpContext.Request.Url;\n            var scheme = urlData.Scheme;//协议\n            var host = urlData.Host;//主机名（不带端口）\n            var port = urlData.Port;//端口\n            string schemeUpper = scheme.ToUpper();//协议（大写）\n            string baseUrl = httpContext.Request.ApplicationPath;//子站点应用路径\n#else\n            if (httpContext.Request == null)\n            {\n                throw new WeixinNullReferenceException(\"httpContext.Request 不能为null！\", httpContext);\n            }\n\n            var request = httpContext.Request;\n            //var location = new Uri($\"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}\");\n            //var returnUrl = location.AbsoluteUri; //httpContext.Request.Url.ToString();    \n            var returnUrl = request.AbsoluteUri();\n            var urlData = httpContext.Request;\n            var scheme = urlData.Scheme;//协议\n            var host = urlData.Host.Host;//主机名（不带端口）\n            var port = urlData.Host.Port ?? -1;//端口（因为从.NET Framework移植，因此不直接使用urlData.Host）\n            string schemeUpper = scheme.ToUpper();//协议（大写）\n            string baseUrl = httpContext.Request.PathBase;//子站点应用路径\n#endif\n\n            //授权回调字符串\n            var callbackUrl = Senparc.Weixin.HttpUtility.UrlUtility.GenerateOAuthCallbackUrl(scheme, host, port, baseUrl, returnUrl, oauthCallbackUrl);\n            return callbackUrl;\n        }","sourceCodeStart":82,"sourceCodeEnd":118,"githubUrl":"https://github.com/JeffreySu/WeiXinMPSDK/blob/be573f6f94bdbf718dd5f6cdecb137fbc7ff651e/src/Senparc.Weixin.AspNet/Utilities/HttpUtility/UrlUtility.cs#L82-L118","documentation":"In the ASP.NET Core (non-NET462) branch of GenerateOAuthCallbackUrl, the code requires a non-null HttpContext.Request to read the absolute URI, scheme and host. If httpContext.Request is null it throws WeixinNullReferenceException early with a descriptive message. This prevents downstream null failures while composing the OAuth callback URL.","triggerScenarios":"Calling GenerateOAuthCallbackUrl on an HttpContext that has no Request object — e.g. a manually constructed HttpContext in tests, or a context taken from outside the middleware pipeline.","commonSituations":"Unit tests with mock HttpContext lacking a Request property, integration code caching an HttpContext after the request ended, custom middleware passing a stripped context.","solutions":["Ensure the call happens within a real ASP.NET Core request where HttpContext.Request is set","Guard with httpContext?.Request == null check before invoking","In tests use DefaultHttpContext() which provides a populated Request","If the request has already completed, capture the needed URL data during the request lifetime instead"],"exampleFix":"// before\nvar callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, \"callback\");\n// after\nif (httpContext?.Request == null)\n{\n    throw new InvalidOperationException(\"GenerateOAuthCallbackUrl requires a live HttpContext.Request\");\n}\nvar callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, \"callback\");","handlingStrategy":"type-guard","validationCode":"if (httpContext?.Request == null) throw new InvalidOperationException(\"GenerateOAuthCallbackUrl requires HttpContext.Request\");","typeGuard":"bool HasRequest(HttpContext ctx) => ctx?.Request != null;","tryCatchPattern":"try { var url = UrlUtility.GenerateOAuthCallbackUrl(httpContext, \"oauthCallback\"); }\ncatch (WeixinNullReferenceException ex) { log.Warn(\"HttpContext.Request unavailable\", ex); }","preventionTips":["Call within an active ASP.NET Core request (controller, middleware)","Use DefaultHttpContext() in tests so Request is non-null","Do not pass a disposed/finished HttpContext into OAuth helpers"],"tags":["httpcontext","oauth","null-reference","asp-net-core"],"backgroundTag":"null-argument","analyzedSha":"be573f6f94bdbf718dd5f6cdecb137fbc7ff651e","analyzedAt":"2026-09-12T10:01:50.733Z","contentChangedAt":"2026-09-12T10:01:50.733Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}