2 // System.Web.HttpContext.cs
5 // Miguel de Icaza (miguel@novell.com)
6 // Gonzalo Paniagua Javier (gonzalo@novell.com)
7 // Marek Habersack <mhabersack@novell.com>
11 // Copyright (C) 2005-2009 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections;
34 using System.Configuration;
35 using System.Globalization;
36 using System.Runtime.Remoting.Messaging;
37 using System.Security.Permissions;
38 using System.Security.Principal;
39 using System.Threading;
40 using System.Web.Caching;
41 using System.Web.Configuration;
42 using System.Web.SessionState;
44 using System.Web.Util;
45 using System.Reflection;
46 using System.Collections.Generic;
48 using System.Resources;
49 using System.Web.Compilation;
50 using System.Web.Profile;
51 using CustomErrorMode = System.Web.Configuration.CustomErrorsMode;
55 // CAS - no InheritanceDemand here as the class is sealed
56 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
57 public sealed partial class HttpContext : IServiceProvider
59 internal HttpWorkerRequest WorkerRequest;
60 HttpApplication app_instance;
62 HttpResponse response;
63 HttpSessionState session_state;
64 HttpServerUtility server;
65 TraceContext trace_context;
68 bool skip_authorization = false;
72 object config_timeout;
74 DateTime time_stamp = DateTime.UtcNow;
77 bool _isProcessingInclude;
80 static ResourceProviderFactory provider_factory;
83 static DefaultResourceProviderFactory default_provider_factory;
86 static Dictionary <string, IResourceProvider> resource_providers;
89 const string app_global_res_key = "HttpContext.app_global_res_key";
90 internal static Assembly AppGlobalResourcesAssembly {
91 get { return (Assembly) AppDomain.CurrentDomain.GetData (app_global_res_key); }
92 set { AppDomain.CurrentDomain.SetData (app_global_res_key, value); }
95 internal static Assembly AppGlobalResourcesAssembly;
97 ProfileBase profile = null;
98 LinkedList<IHttpHandler> handlers;
100 static DefaultResourceProviderFactory DefaultProviderFactory {
102 if (default_provider_factory == null)
103 default_provider_factory = new DefaultResourceProviderFactory ();
104 return default_provider_factory;
108 public HttpContext (HttpWorkerRequest wr)
111 request = new HttpRequest (WorkerRequest, this);
112 response = new HttpResponse (WorkerRequest, this);
114 SessionStateBehavior = SessionStateBehavior.Default;
118 public HttpContext (HttpRequest request, HttpResponse response)
120 this.request = request;
121 this.response = response;
123 SessionStateBehavior = SessionStateBehavior.Default;
127 internal bool IsProcessingInclude {
128 get { return _isProcessingInclude; }
129 set { _isProcessingInclude = value; }
132 public Exception [] AllErrors {
137 if (errors is Exception){
138 Exception [] all = new Exception [1];
139 all [0] = (Exception) errors;
142 return (Exception []) (((ArrayList) errors).ToArray (typeof (Exception)));
146 public HttpApplicationState Application {
148 return HttpApplicationFactory.ApplicationState;
152 public HttpApplication ApplicationInstance {
158 app_instance = value;
165 return HttpRuntime.Cache;
169 internal Cache InternalCache {
171 return HttpRuntime.InternalCache;
176 // The "Current" property is set just after we have constructed it with
177 // the 'HttpContext (HttpWorkerRequest)' constructor.
179 #if !TARGET_JVM // No remoting CallContext support in Grasshopper
180 public static HttpContext Current {
182 return (HttpContext) CallContext.GetData ("c");
186 CallContext.SetData ("c", value);
191 public Exception Error {
193 if (errors == null || (errors is Exception))
194 return (Exception) errors;
195 return (Exception) (((ArrayList) errors) [0]);
199 public IHttpHandler Handler {
209 public bool IsCustomErrorEnabled {
212 return IsCustomErrorEnabledUnsafe;
220 internal bool IsCustomErrorEnabledUnsafe {
222 CustomErrorsSection cfg = (CustomErrorsSection) WebConfigurationManager.GetSection ("system.web/customErrors");
223 if (cfg.Mode == CustomErrorMode.On)
226 return (cfg.Mode == CustomErrorMode.RemoteOnly) && !Request.IsLocal;
230 public bool IsDebuggingEnabled {
231 get { return RuntimeHelpers.DebuggingEnabled; }
234 public IDictionary Items {
237 items = new Hashtable ();
242 public HttpRequest Request {
248 public HttpResponse Response {
254 public HttpServerUtility Server {
257 server = new HttpServerUtility (this);
262 public HttpSessionState Session {
264 return session_state;
268 public bool SkipAuthorization {
270 return skip_authorization;
273 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
275 skip_authorization = value;
279 public DateTime Timestamp {
281 return time_stamp.ToLocalTime ();
285 public TraceContext Trace {
287 if (trace_context == null)
288 trace_context = new TraceContext (this);
289 return trace_context;
293 public IPrincipal User {
298 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
304 internal bool MapRequestHandlerDone {
309 // The two properties below are defined only when the IIS7 integrated mode is used.
310 // They are useless under Mono
311 public RequestNotification CurrentNotification {
312 get { throw new PlatformNotSupportedException ("This property is not supported on Mono."); }
315 public bool IsPostNotification {
316 get { throw new PlatformNotSupportedException ("This property is not supported on Mono."); }
319 internal void PushHandler (IHttpHandler handler)
323 if (handlers == null)
324 handlers = new LinkedList <IHttpHandler> ();
325 handlers.AddLast (handler);
328 internal void PopHandler ()
330 if (handlers == null || handlers.Count == 0)
332 handlers.RemoveLast ();
335 IHttpHandler GetCurrentHandler ()
337 if (handlers == null || handlers.Count == 0)
340 return handlers.Last.Value;
343 IHttpHandler GetPreviousHandler ()
345 if (handlers == null || handlers.Count <= 1)
347 LinkedListNode <IHttpHandler> previous = handlers.Last.Previous;
348 if (previous != null)
349 return previous.Value;
353 public IHttpHandler CurrentHandler {
354 get { return GetCurrentHandler (); }
357 public IHttpHandler PreviousHandler {
358 get { return GetPreviousHandler (); }
361 internal bool ProfileInitialized {
362 get { return profile != null; }
365 public ProfileBase Profile {
367 if (profile == null) {
368 if (Request.IsAuthenticated)
369 profile = ProfileBase.Create (User.Identity.Name);
371 profile = ProfileBase.Create (Request.AnonymousID, false);
381 public void AddError (Exception errorInfo)
388 if (errors is Exception){
389 l = new ArrayList ();
393 l = (ArrayList) errors;
397 internal void ClearError (Exception e)
403 internal bool HasError (Exception e)
408 return (errors is ArrayList) ?
409 ((ArrayList) errors).Contains (e) : false;
412 public void ClearError ()
417 [Obsolete ("use WebConfigurationManager.GetWebApplicationSection")]
418 public static object GetAppConfig (string name)
420 object o = ConfigurationSettings.GetConfig (name);
425 [Obsolete ("see GetSection")]
426 public object GetConfig (string name)
428 return GetSection (name);
431 public static object GetGlobalResourceObject (string classKey, string resourceKey)
433 return GetGlobalResourceObject (classKey, resourceKey, Thread.CurrentThread.CurrentUICulture);
436 static bool EnsureProviderFactory ()
438 if (resource_providers == null)
439 resource_providers = new Dictionary <string, IResourceProvider> ();
441 if (provider_factory != null)
444 GlobalizationSection gs = WebConfigurationManager.GetSection ("system.web/globalization") as GlobalizationSection;
449 String rsfTypeName = gs.ResourceProviderFactoryType;
450 bool usingDefault = false;
451 if (String.IsNullOrEmpty (rsfTypeName)) {
453 rsfTypeName = typeof (DefaultResourceProviderFactory).AssemblyQualifiedName;
456 Type rsfType = HttpApplication.LoadType (rsfTypeName, true);
457 ResourceProviderFactory rpf = Activator.CreateInstance (rsfType) as ResourceProviderFactory;
459 if (rpf == null && usingDefault)
462 provider_factory = rpf;
464 default_provider_factory = rpf as DefaultResourceProviderFactory;
469 internal static IResourceProvider GetResourceProvider (string virtualPath, bool isLocal)
471 if (!EnsureProviderFactory ())
474 // TODO: check if it makes sense to cache the providers and, if yes, maybe
475 // we should expire the entries (or just store them in InternalCache?)
476 IResourceProvider rp = null;
477 if (!resource_providers.TryGetValue (virtualPath, out rp)) {
479 rp = provider_factory.CreateLocalResourceProvider (virtualPath);
481 rp = provider_factory.CreateGlobalResourceProvider (virtualPath);
485 rp = DefaultProviderFactory.CreateLocalResourceProvider (virtualPath);
487 rp = DefaultProviderFactory.CreateGlobalResourceProvider (virtualPath);
493 resource_providers.Add (virtualPath, rp);
499 static object GetGlobalObjectFromFactory (string classKey, string resourceKey, CultureInfo culture)
501 // FIXME: Retention of data
502 IResourceProvider rp = GetResourceProvider (classKey, false);
506 return rp.GetObject (resourceKey, culture);
509 public static object GetGlobalResourceObject (string classKey, string resourceKey, CultureInfo culture)
511 return GetGlobalObjectFromFactory ("Resources." + classKey, resourceKey, culture);
514 public static object GetLocalResourceObject (string virtualPath, string resourceKey)
516 return GetLocalResourceObject (virtualPath, resourceKey, Thread.CurrentThread.CurrentUICulture);
519 static object GetLocalObjectFromFactory (string virtualPath, string resourceKey, CultureInfo culture)
521 IResourceProvider rp = GetResourceProvider (virtualPath, true);
525 return rp.GetObject (resourceKey, culture);
528 public static object GetLocalResourceObject (string virtualPath, string resourceKey, CultureInfo culture)
530 if (!VirtualPathUtility.IsAbsolute (virtualPath))
531 throw new ArgumentException ("The specified virtualPath was not rooted.");
533 return GetLocalObjectFromFactory (virtualPath, resourceKey, culture);
536 public object GetSection (string name)
538 return WebConfigurationManager.GetSection (name);
541 object IServiceProvider.GetService (Type service)
543 if (service == typeof (HttpWorkerRequest))
544 return WorkerRequest;
547 // We return everything out of properties in case
548 // they are dynamically computed in some form in the future.
550 if (service == typeof (HttpApplication))
551 return ApplicationInstance;
553 if (service == typeof (HttpRequest))
556 if (service == typeof (HttpResponse))
559 if (service == typeof (HttpSessionState))
562 if (service == typeof (HttpApplicationState))
565 if (service == typeof (IPrincipal))
568 if (service == typeof (Cache))
571 if (service == typeof (HttpContext))
574 if (service == typeof (IHttpHandler))
577 if (service == typeof (HttpServerUtility))
580 if (service == typeof (TraceContext))
586 public void RemapHandler (IHttpHandler handler)
588 if (MapRequestHandlerDone)
589 throw new InvalidOperationException ("The RemapHandler method was called after the MapRequestHandler event occurred.");
593 public void RewritePath (string path)
595 RewritePath (path, true);
598 public void RewritePath (string filePath, string pathInfo, string queryString)
600 RewritePath (filePath, pathInfo, queryString, false);
603 public void RewritePath (string path, bool rebaseClientPath)
605 int qmark = path.IndexOf ('?');
607 RewritePath (path.Substring (0, qmark), String.Empty, path.Substring (qmark + 1), rebaseClientPath);
609 RewritePath (path, null, null, rebaseClientPath);
612 public void RewritePath (string filePath, string pathInfo, string queryString, bool setClientFilePath)
614 if (filePath == null)
615 throw new ArgumentNullException ("filePath");
616 if (!VirtualPathUtility.IsValidVirtualPath (filePath))
617 throw new HttpException ("'" + HttpUtility.HtmlEncode (filePath) + "' is not a valid virtual path.");
619 bool pathRelative = VirtualPathUtility.IsAppRelative (filePath);
620 bool pathAbsolute = pathRelative ? false : VirtualPathUtility.IsAbsolute (filePath);
621 HttpRequest req = Request;
625 if (pathRelative || pathAbsolute) {
627 filePath = VirtualPathUtility.ToAbsolute (filePath);
629 filePath = VirtualPathUtility.AppendTrailingSlash (req.BaseVirtualDir) + filePath;
631 if (!StrUtils.StartsWith (filePath, HttpRuntime.AppDomainAppVirtualPath))
632 throw new HttpException (404, "The virtual path '" + HttpUtility.HtmlEncode (filePath) + "' maps to another application.", filePath);
634 req.SetCurrentExePath (filePath);
635 req.SetFilePath (filePath);
637 if (setClientFilePath)
638 req.ClientFilePath = filePath;
640 // A null pathInfo or queryString is ignored and previous values remain untouched
641 if (pathInfo != null)
642 req.SetPathInfo (pathInfo);
644 if (queryString != null)
645 req.QueryStringRaw = queryString;
649 public void SetSessionStateBehavior (SessionStateBehavior sessionStateBehavior)
651 SessionStateBehavior = sessionStateBehavior;
656 internal void SetSession (HttpSessionState state)
658 session_state = state;
661 // URL of a page used for error redirection.
662 internal string ErrorPage {
672 internal TimeSpan ConfigTimeout {
674 if (config_timeout == null) {
675 HttpRuntimeSection section = (HttpRuntimeSection)WebConfigurationManager.GetSection ("system.web/httpRuntime");
676 config_timeout = section.ExecutionTimeout;
679 return (TimeSpan) config_timeout;
683 config_timeout = value;
686 TimeSpan remaining = value - (DateTime.UtcNow - time_stamp);
687 long remaining_ms = Math.Max ((long)remaining.TotalMilliseconds, 0);
689 // See http://msdn2.microsoft.com/en-us/library/7hs7492w.aspx
690 if (remaining_ms > 4294967294)
691 remaining_ms = 4294967294;
693 timer.Change (remaining_ms, (long)Timeout.Infinite);
700 internal SessionStateBehavior SessionStateBehavior {
707 void TimeoutReached(object state) {
708 HttpRuntime.QueuePendingRequest (false);
709 if (Interlocked.CompareExchange (ref timeout_possible, 0, 0) == 0) {
710 timer.Change(2000, 0);
715 thread.Abort (new StepTimeout ());
718 internal void StartTimeoutTimer() {
719 thread = Thread.CurrentThread;
720 timer = new Timer (TimeoutReached, null, (int)ConfigTimeout.TotalMilliseconds, Timeout.Infinite);
723 internal void StopTimeoutTimer() {
730 internal bool TimeoutPossible {
731 get { return (Interlocked.CompareExchange (ref timeout_possible, 1, 1) == 1); }
734 internal void BeginTimeoutPossible ()
736 timeout_possible = 1;
739 internal void EndTimeoutPossible ()
741 Interlocked.CompareExchange (ref timeout_possible, 0, 1);