2 // System.Web.HttpContext.cs
5 // Miguel de Icaza (miguel@novell.com)
6 // Gonzalo Paniagua Javier (gonzalo@novell.com)
10 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
33 using System.Configuration;
34 using System.Globalization;
35 using System.Runtime.Remoting.Messaging;
36 using System.Security.Permissions;
37 using System.Security.Principal;
38 using System.Threading;
39 using System.Web.Caching;
40 using System.Web.Configuration;
41 using System.Web.SessionState;
43 using System.Web.Util;
45 using System.Collections.Generic;
47 using System.Reflection;
48 using System.Resources;
49 using System.Web.Compilation;
50 using System.Web.Profile;
51 using CustomErrorMode = System.Web.Configuration.CustomErrorsMode;
54 namespace System.Web {
55 // CAS - no InheritanceDemand here as the class is sealed
56 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
57 public sealed partial class HttpContext : IServiceProvider {
58 internal HttpWorkerRequest WorkerRequest;
59 HttpApplication app_instance;
61 HttpResponse response;
62 HttpSessionState session_state;
63 HttpServerUtility server;
64 TraceContext trace_context;
67 bool skip_authorization = false;
71 object config_timeout;
73 DateTime time_stamp = DateTime.UtcNow;
76 bool _isProcessingInclude;
81 const string app_global_res_key = "HttpContext.app_global_res_key";
82 internal static Assembly AppGlobalResourcesAssembly {
83 get { return (Assembly) AppDomain.CurrentDomain.GetData (app_global_res_key); }
84 set { AppDomain.CurrentDomain.SetData (app_global_res_key, value); }
87 static Hashtable resourceManagerCache = new Hashtable ();
88 RequestNotification _currentNotification;
89 internal static Assembly AppGlobalResourcesAssembly;
91 ProfileBase profile = null;
92 LinkedList<IHttpHandler> handlers;
95 public HttpContext (HttpWorkerRequest wr)
98 request = new HttpRequest (WorkerRequest, this);
99 response = new HttpResponse (WorkerRequest, this);
102 public HttpContext (HttpRequest request, HttpResponse response)
104 this.request = request;
105 this.response = response;
109 internal bool IsProcessingInclude {
110 get { return _isProcessingInclude; }
111 set { _isProcessingInclude = value; }
114 public Exception [] AllErrors {
119 if (errors is Exception){
120 Exception [] all = new Exception [1];
121 all [0] = (Exception) errors;
124 return (Exception []) (((ArrayList) errors).ToArray (typeof (Exception)));
128 public HttpApplicationState Application {
130 return HttpApplicationFactory.ApplicationState;
134 public HttpApplication ApplicationInstance {
140 app_instance = value;
147 return HttpRuntime.Cache;
151 internal Cache InternalCache {
153 return HttpRuntime.InternalCache;
158 // The "Current" property is set just after we have constructed it with
159 // the 'HttpContext (HttpWorkerRequest)' constructor.
161 #if !TARGET_JVM // No remoting CallContext support in Grasshopper
162 public static HttpContext Current {
164 return (HttpContext) CallContext.GetData ("c");
168 CallContext.SetData ("c", value);
173 public Exception Error {
175 if (errors == null || (errors is Exception))
176 return (Exception) errors;
177 return (Exception) (((ArrayList) errors) [0]);
181 public IHttpHandler Handler {
191 public bool IsCustomErrorEnabled {
194 return IsCustomErrorEnabledUnsafe;
202 internal bool IsCustomErrorEnabledUnsafe {
205 CustomErrorsSection cfg = (CustomErrorsSection) WebConfigurationManager.GetSection ("system.web/customErrors");
207 CustomErrorsConfig cfg = null;
209 cfg = (CustomErrorsConfig) GetConfig ("system.web/customErrors");
217 if (cfg.Mode == CustomErrorMode.On)
220 return (cfg.Mode == CustomErrorMode.RemoteOnly) && !Request.IsLocal;
224 public bool IsDebuggingEnabled {
227 CompilationSection section = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
228 return section.Debug;
231 return CompilationConfiguration.GetInstance (this).Debug;
239 public IDictionary Items {
242 items = new Hashtable ();
247 public HttpRequest Request {
253 public HttpResponse Response {
259 public HttpServerUtility Server {
262 server = new HttpServerUtility (this);
267 public HttpSessionState Session {
269 return session_state;
273 public bool SkipAuthorization {
275 return skip_authorization;
278 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
280 skip_authorization = value;
284 public DateTime Timestamp {
286 return time_stamp.ToLocalTime ();
290 public TraceContext Trace {
292 if (trace_context == null)
293 trace_context = new TraceContext (this);
294 return trace_context;
298 public IPrincipal User {
303 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
310 // The two properties below are defined only when the IIS7 integrated mode is used.
311 // They are useless under Mono
312 public RequestNotification CurrentNotification {
313 get { throw new PlatformNotSupportedException ("This property is not supported on Mono."); }
316 public bool IsPostNotification {
317 get { throw new PlatformNotSupportedException ("This property is not supported on Mono."); }
320 internal void PushHandler (IHttpHandler handler)
324 if (handlers == null)
325 handlers = new LinkedList <IHttpHandler> ();
326 handlers.AddLast (handler);
329 internal void PopHandler ()
331 if (handlers == null || handlers.Count == 0)
333 handlers.RemoveLast ();
336 IHttpHandler GetCurrentHandler ()
338 if (handlers == null || handlers.Count == 0)
341 return handlers.Last.Value;
344 IHttpHandler GetPreviousHandler ()
346 if (handlers == null || handlers.Count <= 1)
348 LinkedListNode <IHttpHandler> previous = handlers.Last.Previous;
349 if (previous != null)
350 return previous.Value;
354 public IHttpHandler CurrentHandler {
355 get { return GetCurrentHandler (); }
358 public IHttpHandler PreviousHandler {
359 get { return GetPreviousHandler (); }
362 internal bool ProfileInitialized {
363 get { return profile != null; }
366 public ProfileBase Profile {
368 if (profile == null) {
369 if (Request.IsAuthenticated)
370 profile = ProfileBase.Create (User.Identity.Name);
372 profile = ProfileBase.Create (Request.AnonymousID, false);
383 public void AddError (Exception errorInfo)
390 if (errors is Exception){
391 l = new ArrayList ();
395 l = (ArrayList) errors;
399 internal void ClearError (Exception e)
405 internal bool HasError (Exception e)
410 return (errors is ArrayList) ?
411 ((ArrayList) errors).Contains (e) : false;
414 public void ClearError ()
420 [Obsolete ("use WebConfigurationManager.GetWebApplicationSection")]
422 public static object GetAppConfig (string name)
424 object o = ConfigurationSettings.GetConfig (name);
430 [Obsolete ("see GetSection")]
432 public object GetConfig (string name)
435 return GetSection (name);
437 return WebConfigurationSettings.GetConfig (name, this);
442 static object GetResourceObject (string classKey, string resourceKey, CultureInfo culture, Assembly assembly)
446 ResourceManagerCacheKey key = new ResourceManagerCacheKey (classKey, assembly);
447 rm = (ResourceManager) resourceManagerCache [key];
450 rm = new ResourceManager (classKey, assembly);
451 rm.IgnoreCase = true;
452 Hashtable tmp = (Hashtable) resourceManagerCache.Clone ();
454 resourceManagerCache = tmp;
457 return rm.GetObject (resourceKey, culture);
458 } catch (MissingManifestResourceException) {
460 } catch (Exception ex) {
461 throw new HttpException ("Failed to retrieve the specified global resource object.", ex);
465 public static object GetGlobalResourceObject (string classKey, string resourceKey)
467 return GetGlobalResourceObject (classKey, resourceKey, Thread.CurrentThread.CurrentUICulture);
470 public static object GetGlobalResourceObject (string classKey, string resourceKey, CultureInfo culture)
472 if (AppGlobalResourcesAssembly == null)
473 throw new MissingManifestResourceException ();
474 return GetResourceObject ("Resources." + classKey, resourceKey, culture, AppGlobalResourcesAssembly);
477 public static object GetLocalResourceObject (string virtualPath, string resourceKey)
479 return GetLocalResourceObject (virtualPath, resourceKey, Thread.CurrentThread.CurrentUICulture);
482 public static object GetLocalResourceObject (string virtualPath, string resourceKey, CultureInfo culture)
484 if (!VirtualPathUtility.IsAbsolute (virtualPath))
485 throw new ArgumentException ("The specified virtualPath was not rooted.");
487 string path = Path.GetDirectoryName (virtualPath);
488 Assembly asm = AppResourcesCompiler.GetCachedLocalResourcesAssembly (path);
490 AppResourcesCompiler ac = new AppResourcesCompiler (path);
493 throw new MissingManifestResourceException ("A resource object was not found at the specified virtualPath.");
496 path = Path.GetFileName (virtualPath);
497 return GetResourceObject (path, resourceKey, culture, asm);
500 public object GetSection (string name)
502 return WebConfigurationManager.GetSection (name);
505 private sealed class ResourceManagerCacheKey
507 readonly string _name;
508 readonly Assembly _asm;
510 public ResourceManagerCacheKey (string name, Assembly asm)
516 public override bool Equals (object obj)
518 if (!(obj is ResourceManagerCacheKey))
520 ResourceManagerCacheKey key = (ResourceManagerCacheKey) obj;
521 return key._asm == _asm && _name.Equals (key._name, StringComparison.Ordinal);
524 public override int GetHashCode ()
526 return _name.GetHashCode () + _asm.GetHashCode ();
530 object IServiceProvider.GetService (Type service)
532 if (service == typeof (HttpWorkerRequest))
533 return WorkerRequest;
536 // We return everything out of properties in case
537 // they are dynamically computed in some form in the future.
539 if (service == typeof (HttpApplication))
540 return ApplicationInstance;
542 if (service == typeof (HttpRequest))
545 if (service == typeof (HttpResponse))
548 if (service == typeof (HttpSessionState))
551 if (service == typeof (HttpApplicationState))
554 if (service == typeof (IPrincipal))
557 if (service == typeof (Cache))
560 if (service == typeof (HttpContext))
563 if (service == typeof (IHttpHandler))
566 if (service == typeof (HttpServerUtility))
569 if (service == typeof (TraceContext))
575 public void RewritePath (string path)
578 RewritePath (path, true);
580 RewritePath (path, false);
584 public void RewritePath (string filePath, string pathInfo, string queryString)
586 RewritePath (filePath, pathInfo, queryString, false);
594 void RewritePath (string path, bool rebaseClientPath)
596 int qmark = path.IndexOf ('?');
598 RewritePath (path.Substring (0, qmark), "", path.Substring (qmark + 1), rebaseClientPath);
600 RewritePath (path, null, null, rebaseClientPath);
608 void RewritePath (string filePath, string pathInfo, string queryString, bool setClientFilePath)
610 filePath = UrlUtils.Combine (Request.BaseVirtualDir, filePath);
611 if (!StrUtils.StartsWith (filePath, HttpRuntime.AppDomainAppVirtualPath))
612 throw new HttpException (404, "The virtual path '" + filePath + "' maps to another application.", filePath);
614 Request.SetCurrentExePath (filePath);
615 // A null pathInfo or queryString is ignored and previous values remain untouched
616 if (pathInfo != null)
617 Request.SetPathInfo (pathInfo);
619 if (queryString != null)
620 Request.QueryStringRaw = queryString;
622 if (setClientFilePath)
623 Request.SetFilePath (filePath);
629 internal void SetSession (HttpSessionState state)
631 session_state = state;
634 // URL of a page used for error redirection.
635 internal string ErrorPage {
645 internal TimeSpan ConfigTimeout {
647 if (config_timeout == null) {
649 HttpRuntimeSection section = (HttpRuntimeSection)WebConfigurationManager.GetSection ("system.web/httpRuntime");
650 config_timeout = section.ExecutionTimeout;
652 HttpRuntimeConfig config = (HttpRuntimeConfig)
653 GetConfig ("system.web/httpRuntime");
654 config_timeout = new TimeSpan (0, 0, config.ExecutionTimeout);
658 return (TimeSpan) config_timeout;
662 config_timeout = value;
665 TimeSpan remaining = value - (DateTime.UtcNow - time_stamp);
666 long remaining_ms = Math.Max ((long)remaining.TotalMilliseconds, 0);
668 // See http://msdn2.microsoft.com/en-us/library/7hs7492w.aspx
669 if (remaining_ms > 4294967294)
670 remaining_ms = 4294967294;
672 timer.Change (remaining_ms, (long)Timeout.Infinite);
679 void TimeoutReached(object state) {
680 if (Interlocked.CompareExchange (ref timeout_possible, 0, 0) == 0) {
681 timer.Change(2000, 0);
686 thread.Abort (new StepTimeout ());
689 internal void StartTimeoutTimer() {
690 thread = Thread.CurrentThread;
691 timer = new Timer (TimeoutReached, null, (int)ConfigTimeout.TotalMilliseconds, Timeout.Infinite);
694 internal void StopTimeoutTimer() {
701 internal bool TimeoutPossible {
702 get { return (Interlocked.CompareExchange (ref timeout_possible, 1, 1) == 1); }
705 internal void BeginTimeoutPossible ()
707 timeout_possible = 1;
710 internal void EndTimeoutPossible ()
712 Interlocked.CompareExchange (ref timeout_possible, 0, 1);