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;
80 static ResourceProviderFactory provider_factory;
82 static Dictionary <string, IResourceProvider> resource_providers;
85 const string app_global_res_key = "HttpContext.app_global_res_key";
86 internal static Assembly AppGlobalResourcesAssembly {
87 get { return (Assembly) AppDomain.CurrentDomain.GetData (app_global_res_key); }
88 set { AppDomain.CurrentDomain.SetData (app_global_res_key, value); }
92 static Dictionary <ResourceManagerCacheKey, ResourceManager> resourceManagerCache;
93 internal static Assembly AppGlobalResourcesAssembly;
95 ProfileBase profile = null;
96 LinkedList<IHttpHandler> handlers;
99 public HttpContext (HttpWorkerRequest wr)
102 request = new HttpRequest (WorkerRequest, this);
103 response = new HttpResponse (WorkerRequest, this);
106 public HttpContext (HttpRequest request, HttpResponse response)
108 this.request = request;
109 this.response = response;
113 internal bool IsProcessingInclude {
114 get { return _isProcessingInclude; }
115 set { _isProcessingInclude = value; }
118 public Exception [] AllErrors {
123 if (errors is Exception){
124 Exception [] all = new Exception [1];
125 all [0] = (Exception) errors;
128 return (Exception []) (((ArrayList) errors).ToArray (typeof (Exception)));
132 public HttpApplicationState Application {
134 return HttpApplicationFactory.ApplicationState;
138 public HttpApplication ApplicationInstance {
144 app_instance = value;
151 return HttpRuntime.Cache;
155 internal Cache InternalCache {
157 return HttpRuntime.InternalCache;
162 // The "Current" property is set just after we have constructed it with
163 // the 'HttpContext (HttpWorkerRequest)' constructor.
165 #if !TARGET_JVM // No remoting CallContext support in Grasshopper
166 public static HttpContext Current {
168 return (HttpContext) CallContext.GetData ("c");
172 CallContext.SetData ("c", value);
177 public Exception Error {
179 if (errors == null || (errors is Exception))
180 return (Exception) errors;
181 return (Exception) (((ArrayList) errors) [0]);
185 public IHttpHandler Handler {
195 public bool IsCustomErrorEnabled {
198 return IsCustomErrorEnabledUnsafe;
206 internal bool IsCustomErrorEnabledUnsafe {
209 CustomErrorsSection cfg = (CustomErrorsSection) WebConfigurationManager.GetSection ("system.web/customErrors");
211 CustomErrorsConfig cfg = null;
213 cfg = (CustomErrorsConfig) GetConfig ("system.web/customErrors");
221 if (cfg.Mode == CustomErrorMode.On)
224 return (cfg.Mode == CustomErrorMode.RemoteOnly) && !Request.IsLocal;
228 public bool IsDebuggingEnabled {
231 CompilationSection section = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
232 return section.Debug;
235 return CompilationConfiguration.GetInstance (this).Debug;
243 public IDictionary Items {
246 items = new Hashtable ();
251 public HttpRequest Request {
257 public HttpResponse Response {
263 public HttpServerUtility Server {
266 server = new HttpServerUtility (this);
271 public HttpSessionState Session {
273 return session_state;
277 public bool SkipAuthorization {
279 return skip_authorization;
282 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
284 skip_authorization = value;
288 public DateTime Timestamp {
290 return time_stamp.ToLocalTime ();
294 public TraceContext Trace {
296 if (trace_context == null)
297 trace_context = new TraceContext (this);
298 return trace_context;
302 public IPrincipal User {
307 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
314 // The two properties below are defined only when the IIS7 integrated mode is used.
315 // They are useless under Mono
316 public RequestNotification CurrentNotification {
317 get { throw new PlatformNotSupportedException ("This property is not supported on Mono."); }
320 public bool IsPostNotification {
321 get { throw new PlatformNotSupportedException ("This property is not supported on Mono."); }
324 internal void PushHandler (IHttpHandler handler)
328 if (handlers == null)
329 handlers = new LinkedList <IHttpHandler> ();
330 handlers.AddLast (handler);
333 internal void PopHandler ()
335 if (handlers == null || handlers.Count == 0)
337 handlers.RemoveLast ();
340 IHttpHandler GetCurrentHandler ()
342 if (handlers == null || handlers.Count == 0)
345 return handlers.Last.Value;
348 IHttpHandler GetPreviousHandler ()
350 if (handlers == null || handlers.Count <= 1)
352 LinkedListNode <IHttpHandler> previous = handlers.Last.Previous;
353 if (previous != null)
354 return previous.Value;
358 public IHttpHandler CurrentHandler {
359 get { return GetCurrentHandler (); }
362 public IHttpHandler PreviousHandler {
363 get { return GetPreviousHandler (); }
366 internal bool ProfileInitialized {
367 get { return profile != null; }
370 public ProfileBase Profile {
372 if (profile == null) {
373 if (Request.IsAuthenticated)
374 profile = ProfileBase.Create (User.Identity.Name);
376 profile = ProfileBase.Create (Request.AnonymousID, false);
387 public void AddError (Exception errorInfo)
394 if (errors is Exception){
395 l = new ArrayList ();
399 l = (ArrayList) errors;
403 internal void ClearError (Exception e)
409 internal bool HasError (Exception e)
414 return (errors is ArrayList) ?
415 ((ArrayList) errors).Contains (e) : false;
418 public void ClearError ()
424 [Obsolete ("use WebConfigurationManager.GetWebApplicationSection")]
426 public static object GetAppConfig (string name)
428 object o = ConfigurationSettings.GetConfig (name);
434 [Obsolete ("see GetSection")]
436 public object GetConfig (string name)
439 return GetSection (name);
441 return WebConfigurationSettings.GetConfig (name, this);
446 static object GetResourceObject (string classKey, string resourceKey, CultureInfo culture, Assembly assembly)
450 if (resourceManagerCache == null)
451 resourceManagerCache = new Dictionary <ResourceManagerCacheKey, ResourceManager> ();
453 ResourceManagerCacheKey key = new ResourceManagerCacheKey (classKey, assembly);
454 if (!resourceManagerCache.TryGetValue (key, out rm)) {
455 rm = new ResourceManager (classKey, assembly);
456 rm.IgnoreCase = true;
457 resourceManagerCache.Add (key, rm);
460 return rm.GetObject (resourceKey, culture);
461 } catch (MissingManifestResourceException) {
463 } catch (Exception ex) {
464 throw new HttpException ("Failed to retrieve the specified global resource object.", ex);
468 public static object GetGlobalResourceObject (string classKey, string resourceKey)
470 return GetGlobalResourceObject (classKey, resourceKey, Thread.CurrentThread.CurrentUICulture);
473 static object GetGlobalObjectFromFactory (string classKey, string resourceKey, CultureInfo culture)
475 // FIXME: Retention of data
477 if (provider_factory == null) {
478 GlobalizationSection gs = WebConfigurationManager.GetSection ("system.web/globalization") as GlobalizationSection;
483 String rsfTypeName = gs.ResourceProviderFactoryType;
484 if (String.IsNullOrEmpty (rsfTypeName))
487 Type rsfType = Type.GetType (rsfTypeName, true);
488 ResourceProviderFactory rpf = Activator.CreateInstance (rsfType) as ResourceProviderFactory;
493 provider_factory = rpf;
496 if (resource_providers == null)
497 resource_providers = new Dictionary <string, IResourceProvider> ();
499 IResourceProvider rp;
500 if (!resource_providers.TryGetValue (classKey, out rp)) {
501 rp = provider_factory.CreateGlobalResourceProvider (classKey);
504 resource_providers.Add (classKey, rp);
507 return rp.GetObject (resourceKey, culture);
510 public static object GetGlobalResourceObject (string classKey, string resourceKey, CultureInfo culture)
512 object ret = GetGlobalObjectFromFactory (classKey, resourceKey, culture);
516 if (AppGlobalResourcesAssembly == null)
517 throw new MissingManifestResourceException ();
519 return GetResourceObject ("Resources." + classKey, resourceKey, culture, AppGlobalResourcesAssembly);
522 public static object GetLocalResourceObject (string virtualPath, string resourceKey)
524 return GetLocalResourceObject (virtualPath, resourceKey, Thread.CurrentThread.CurrentUICulture);
527 public static object GetLocalResourceObject (string virtualPath, string resourceKey, CultureInfo culture)
529 if (!VirtualPathUtility.IsAbsolute (virtualPath))
530 throw new ArgumentException ("The specified virtualPath was not rooted.");
532 string path = Path.GetDirectoryName (virtualPath);
533 Assembly asm = AppResourcesCompiler.GetCachedLocalResourcesAssembly (path);
535 AppResourcesCompiler ac = new AppResourcesCompiler (path);
538 throw new MissingManifestResourceException ("A resource object was not found at the specified virtualPath.");
541 path = Path.GetFileName (virtualPath);
542 return GetResourceObject (path, resourceKey, culture, asm);
545 public object GetSection (string name)
547 return WebConfigurationManager.GetSection (name);
550 sealed class ResourceManagerCacheKey
552 readonly string _name;
553 readonly Assembly _asm;
555 public ResourceManagerCacheKey (string name, Assembly asm)
561 public override bool Equals (object obj)
563 if (!(obj is ResourceManagerCacheKey))
565 ResourceManagerCacheKey key = (ResourceManagerCacheKey) obj;
566 return key._asm == _asm && _name.Equals (key._name, StringComparison.Ordinal);
569 public override int GetHashCode ()
571 return _name.GetHashCode () + _asm.GetHashCode ();
575 object IServiceProvider.GetService (Type service)
577 if (service == typeof (HttpWorkerRequest))
578 return WorkerRequest;
581 // We return everything out of properties in case
582 // they are dynamically computed in some form in the future.
584 if (service == typeof (HttpApplication))
585 return ApplicationInstance;
587 if (service == typeof (HttpRequest))
590 if (service == typeof (HttpResponse))
593 if (service == typeof (HttpSessionState))
596 if (service == typeof (HttpApplicationState))
599 if (service == typeof (IPrincipal))
602 if (service == typeof (Cache))
605 if (service == typeof (HttpContext))
608 if (service == typeof (IHttpHandler))
611 if (service == typeof (HttpServerUtility))
614 if (service == typeof (TraceContext))
620 public void RewritePath (string path)
623 RewritePath (path, true);
625 RewritePath (path, false);
629 public void RewritePath (string filePath, string pathInfo, string queryString)
631 RewritePath (filePath, pathInfo, queryString, false);
639 void RewritePath (string path, bool rebaseClientPath)
641 int qmark = path.IndexOf ('?');
643 RewritePath (path.Substring (0, qmark), "", path.Substring (qmark + 1), rebaseClientPath);
645 RewritePath (path, null, null, rebaseClientPath);
653 void RewritePath (string filePath, string pathInfo, string queryString, bool setClientFilePath)
655 if (UrlUtils.IsRooted (filePath))
656 filePath = UrlUtils.Combine (Request.BaseVirtualDir, UrlUtils.Canonic (filePath).Substring (1));
658 filePath = UrlUtils.Combine (UrlUtils.GetDirectory (Request.FilePath), filePath);
659 if (!StrUtils.StartsWith (filePath, HttpRuntime.AppDomainAppVirtualPath))
660 throw new HttpException (404, "The virtual path '" + filePath + "' maps to another application.", filePath);
662 Request.SetCurrentExePath (filePath);
663 if (setClientFilePath)
664 Request.SetFilePath (filePath);
666 // A null pathInfo or queryString is ignored and previous values remain untouched
667 if (pathInfo != null)
668 Request.SetPathInfo (pathInfo);
670 if (queryString != null)
671 Request.QueryStringRaw = queryString;
676 internal void SetSession (HttpSessionState state)
678 session_state = state;
681 // URL of a page used for error redirection.
682 internal string ErrorPage {
692 internal TimeSpan ConfigTimeout {
694 if (config_timeout == null) {
696 HttpRuntimeSection section = (HttpRuntimeSection)WebConfigurationManager.GetSection ("system.web/httpRuntime");
697 config_timeout = section.ExecutionTimeout;
699 HttpRuntimeConfig config = (HttpRuntimeConfig)
700 GetConfig ("system.web/httpRuntime");
701 config_timeout = new TimeSpan (0, 0, config.ExecutionTimeout);
705 return (TimeSpan) config_timeout;
709 config_timeout = value;
712 TimeSpan remaining = value - (DateTime.UtcNow - time_stamp);
713 long remaining_ms = Math.Max ((long)remaining.TotalMilliseconds, 0);
715 // See http://msdn2.microsoft.com/en-us/library/7hs7492w.aspx
716 if (remaining_ms > 4294967294)
717 remaining_ms = 4294967294;
719 timer.Change (remaining_ms, (long)Timeout.Infinite);
726 void TimeoutReached(object state) {
727 if (Interlocked.CompareExchange (ref timeout_possible, 0, 0) == 0) {
728 timer.Change(2000, 0);
733 thread.Abort (new StepTimeout ());
736 internal void StartTimeoutTimer() {
737 thread = Thread.CurrentThread;
738 timer = new Timer (TimeoutReached, null, (int)ConfigTimeout.TotalMilliseconds, Timeout.Infinite);
741 internal void StopTimeoutTimer() {
748 internal bool TimeoutPossible {
749 get { return (Interlocked.CompareExchange (ref timeout_possible, 1, 1) == 1); }
752 internal void BeginTimeoutPossible ()
754 timeout_possible = 1;
757 internal void EndTimeoutPossible ()
759 Interlocked.CompareExchange (ref timeout_possible, 0, 1);