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;
88 internal static Assembly AppGlobalResourcesAssembly;
89 ProfileBase profile = null;
90 LinkedList<IHttpHandler> handlers;
92 static DefaultResourceProviderFactory DefaultProviderFactory {
94 if (default_provider_factory == null)
95 default_provider_factory = new DefaultResourceProviderFactory ();
96 return default_provider_factory;
100 public HttpContext (HttpWorkerRequest wr)
103 request = new HttpRequest (WorkerRequest, this);
104 response = new HttpResponse (WorkerRequest, this);
105 SessionStateBehavior = SessionStateBehavior.Default;
108 public HttpContext (HttpRequest request, HttpResponse response)
110 this.request = request;
111 this.response = response;
112 this.request.Context = this;
113 this.response.Context = this;
114 SessionStateBehavior = SessionStateBehavior.Default;
117 internal bool IsProcessingInclude {
118 get { return _isProcessingInclude; }
119 set { _isProcessingInclude = value; }
122 public Exception [] AllErrors {
127 if (errors is Exception){
128 Exception [] all = new Exception [1];
129 all [0] = (Exception) errors;
132 return (Exception []) (((ArrayList) errors).ToArray (typeof (Exception)));
136 public HttpApplicationState Application {
138 return HttpApplicationFactory.ApplicationState;
142 public HttpApplication ApplicationInstance {
148 app_instance = value;
155 return HttpRuntime.Cache;
159 internal Cache InternalCache {
161 return HttpRuntime.InternalCache;
166 // The "Current" property is set just after we have constructed it with
167 // the 'HttpContext (HttpWorkerRequest)' constructor.
169 public static HttpContext Current {
171 return (HttpContext) CallContext.GetData ("c");
175 CallContext.SetData ("c", value);
179 public Exception Error {
181 if (errors == null || (errors is Exception))
182 return (Exception) errors;
183 return (Exception) (((ArrayList) errors) [0]);
187 public IHttpHandler Handler {
197 public bool IsCustomErrorEnabled {
200 return IsCustomErrorEnabledUnsafe;
208 internal bool IsCustomErrorEnabledUnsafe {
210 CustomErrorsSection cfg = (CustomErrorsSection) WebConfigurationManager.GetSection ("system.web/customErrors");
211 if (cfg.Mode == CustomErrorMode.On)
214 return (cfg.Mode == CustomErrorMode.RemoteOnly) && !Request.IsLocal;
217 public bool IsDebuggingEnabled {
218 get { return RuntimeHelpers.DebuggingEnabled; }
220 public IDictionary Items {
223 items = new Hashtable ();
228 public HttpRequest Request {
234 public HttpResponse Response {
240 public HttpServerUtility Server {
243 server = new HttpServerUtility (this);
248 public HttpSessionState Session {
250 return session_state;
254 public bool SkipAuthorization {
256 return skip_authorization;
259 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
261 skip_authorization = value;
265 public DateTime Timestamp {
267 return time_stamp.ToLocalTime ();
271 public TraceContext Trace {
273 if (trace_context == null)
274 trace_context = new TraceContext (this);
275 return trace_context;
279 public IPrincipal User {
284 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
290 internal bool MapRequestHandlerDone {
295 // The two properties below are defined only when the IIS7 integrated mode is used.
296 // They are useless under Mono
297 public RequestNotification CurrentNotification {
298 get { throw new PlatformNotSupportedException ("This property is not supported on Mono."); }
301 public bool IsPostNotification {
302 get { throw new PlatformNotSupportedException ("This property is not supported on Mono."); }
305 internal void PushHandler (IHttpHandler handler)
309 if (handlers == null)
310 handlers = new LinkedList <IHttpHandler> ();
311 handlers.AddLast (handler);
314 internal void PopHandler ()
316 if (handlers == null || handlers.Count == 0)
318 handlers.RemoveLast ();
321 IHttpHandler GetCurrentHandler ()
323 if (handlers == null || handlers.Count == 0)
326 return handlers.Last.Value;
329 IHttpHandler GetPreviousHandler ()
331 if (handlers == null || handlers.Count <= 1)
333 LinkedListNode <IHttpHandler> previous = handlers.Last.Previous;
334 if (previous != null)
335 return previous.Value;
339 public IHttpHandler CurrentHandler {
340 get { return GetCurrentHandler (); }
343 public IHttpHandler PreviousHandler {
344 get { return GetPreviousHandler (); }
347 internal bool ProfileInitialized {
348 get { return profile != null; }
351 public ProfileBase Profile {
353 if (profile == null) {
354 if (Request.IsAuthenticated)
355 profile = ProfileBase.Create (User.Identity.Name);
357 profile = ProfileBase.Create (Request.AnonymousID, false);
367 public void AddError (Exception errorInfo)
374 if (errors is Exception){
375 l = new ArrayList ();
379 l = (ArrayList) errors;
383 internal void ClearError (Exception e)
389 internal bool HasError (Exception e)
394 return (errors is ArrayList) ?
395 ((ArrayList) errors).Contains (e) : false;
398 public void ClearError ()
403 [Obsolete ("The recommended alternative is System.Web.Configuration.WebConfigurationManager.GetWebApplicationSection in System.Web.dll. http://go.microsoft.com/fwlink/?linkid=14202")]
404 public static object GetAppConfig (string name)
406 object o = ConfigurationSettings.GetConfig (name);
411 [Obsolete ("The recommended alternative is System.Web.HttpContext.GetSection in System.Web.dll. http://go.microsoft.com/fwlink/?linkid=14202")]
412 public object GetConfig (string name)
414 return GetSection (name);
417 public static object GetGlobalResourceObject (string classKey, string resourceKey)
419 return GetGlobalResourceObject (classKey, resourceKey, Thread.CurrentThread.CurrentUICulture);
422 static bool EnsureProviderFactory ()
424 if (resource_providers == null)
425 resource_providers = new Dictionary <string, IResourceProvider> ();
427 if (provider_factory != null)
430 GlobalizationSection gs = WebConfigurationManager.GetSection ("system.web/globalization") as GlobalizationSection;
435 String rsfTypeName = gs.ResourceProviderFactoryType;
436 bool usingDefault = false;
437 if (String.IsNullOrEmpty (rsfTypeName)) {
439 rsfTypeName = typeof (DefaultResourceProviderFactory).AssemblyQualifiedName;
442 Type rsfType = HttpApplication.LoadType (rsfTypeName, true);
443 ResourceProviderFactory rpf = Activator.CreateInstance (rsfType) as ResourceProviderFactory;
445 if (rpf == null && usingDefault)
448 provider_factory = rpf;
450 default_provider_factory = rpf as DefaultResourceProviderFactory;
455 internal static IResourceProvider GetResourceProvider (string virtualPath, bool isLocal)
457 if (!EnsureProviderFactory ())
460 // TODO: check if it makes sense to cache the providers and, if yes, maybe
461 // we should expire the entries (or just store them in InternalCache?)
462 IResourceProvider rp = null;
463 if (!resource_providers.TryGetValue (virtualPath, out rp)) {
465 rp = provider_factory.CreateLocalResourceProvider (virtualPath);
467 rp = provider_factory.CreateGlobalResourceProvider (virtualPath);
471 rp = DefaultProviderFactory.CreateLocalResourceProvider (virtualPath);
473 rp = DefaultProviderFactory.CreateGlobalResourceProvider (virtualPath);
479 resource_providers.Add (virtualPath, rp);
485 static object GetGlobalObjectFromFactory (string classKey, string resourceKey, CultureInfo culture)
487 // FIXME: Retention of data
488 IResourceProvider rp = GetResourceProvider (classKey, false);
492 return rp.GetObject (resourceKey, culture);
495 public static object GetGlobalResourceObject (string classKey, string resourceKey, CultureInfo culture)
497 return GetGlobalObjectFromFactory ("Resources." + classKey, resourceKey, culture);
500 public static object GetLocalResourceObject (string virtualPath, string resourceKey)
502 return GetLocalResourceObject (virtualPath, resourceKey, Thread.CurrentThread.CurrentUICulture);
505 static object GetLocalObjectFromFactory (string virtualPath, string resourceKey, CultureInfo culture)
507 IResourceProvider rp = GetResourceProvider (virtualPath, true);
511 return rp.GetObject (resourceKey, culture);
514 public static object GetLocalResourceObject (string virtualPath, string resourceKey, CultureInfo culture)
516 if (!VirtualPathUtility.IsAbsolute (virtualPath))
517 throw new ArgumentException ("The specified virtualPath was not rooted.");
519 return GetLocalObjectFromFactory (virtualPath, resourceKey, culture);
522 public object GetSection (string name)
524 return WebConfigurationManager.GetSection (name);
527 object IServiceProvider.GetService (Type service)
529 if (service == typeof (HttpWorkerRequest))
530 return WorkerRequest;
533 // We return everything out of properties in case
534 // they are dynamically computed in some form in the future.
536 if (service == typeof (HttpApplication))
537 return ApplicationInstance;
539 if (service == typeof (HttpRequest))
542 if (service == typeof (HttpResponse))
545 if (service == typeof (HttpSessionState))
548 if (service == typeof (HttpApplicationState))
551 if (service == typeof (IPrincipal))
554 if (service == typeof (Cache))
557 if (service == typeof (HttpContext))
560 if (service == typeof (IHttpHandler))
563 if (service == typeof (HttpServerUtility))
566 if (service == typeof (TraceContext))
572 public void RemapHandler (IHttpHandler handler)
574 if (MapRequestHandlerDone)
575 throw new InvalidOperationException ("The RemapHandler method was called after the MapRequestHandler event occurred.");
579 public void RewritePath (string path)
581 RewritePath (path, true);
584 public void RewritePath (string filePath, string pathInfo, string queryString)
586 RewritePath (filePath, pathInfo, queryString, false);
589 public void RewritePath (string path, bool rebaseClientPath)
591 int qmark = path.IndexOf ('?');
593 RewritePath (path.Substring (0, qmark), String.Empty, path.Substring (qmark + 1), rebaseClientPath);
595 RewritePath (path, null, null, rebaseClientPath);
598 public void RewritePath (string filePath, string pathInfo, string queryString, bool setClientFilePath)
600 if (filePath == null)
601 throw new ArgumentNullException ("filePath");
602 if (!VirtualPathUtility.IsValidVirtualPath (filePath))
603 throw new HttpException ("'" + HttpUtility.HtmlEncode (filePath) + "' is not a valid virtual path.");
605 filePath = VirtualPathUtility.Canonize (filePath);
606 bool pathRelative = VirtualPathUtility.IsAppRelative (filePath);
607 bool pathAbsolute = pathRelative ? false : VirtualPathUtility.IsAbsolute (filePath);
608 HttpRequest req = Request;
612 if (pathRelative || pathAbsolute) {
614 filePath = VirtualPathUtility.ToAbsolute (filePath);
616 filePath = VirtualPathUtility.AppendTrailingSlash (req.BaseVirtualDir) + filePath;
618 if (!StrUtils.StartsWith (filePath, HttpRuntime.AppDomainAppVirtualPath))
619 throw new HttpException (404, "The virtual path '" + HttpUtility.HtmlEncode (filePath) + "' maps to another application.", filePath);
621 req.SetCurrentExePath (filePath);
622 req.SetFilePath (filePath);
624 if (setClientFilePath)
625 req.ClientFilePath = filePath;
627 // A null pathInfo or queryString is ignored and previous values remain untouched
628 if (pathInfo != null)
629 req.SetPathInfo (pathInfo);
631 if (queryString != null)
632 req.QueryStringRaw = queryString;
635 public void SetSessionStateBehavior (SessionStateBehavior sessionStateBehavior)
637 SessionStateBehavior = sessionStateBehavior;
641 internal void SetSession (HttpSessionState state)
643 session_state = state;
646 // URL of a page used for error redirection.
647 internal string ErrorPage {
657 internal TimeSpan ConfigTimeout {
659 if (config_timeout == null)
660 config_timeout = HttpRuntime.Section.ExecutionTimeout;
662 return (TimeSpan) config_timeout;
666 config_timeout = value;
668 TimeSpan remaining = value - (DateTime.UtcNow - time_stamp);
669 long remaining_ms = Math.Max ((long)remaining.TotalMilliseconds, 0);
671 // See http://msdn2.microsoft.com/en-us/library/7hs7492w.aspx
672 if (remaining_ms > 4294967294)
673 remaining_ms = 4294967294;
675 timer.Change (remaining_ms, (long)Timeout.Infinite);
680 internal SessionStateBehavior SessionStateBehavior {
685 void TimeoutReached(object state) {
686 HttpRuntime.QueuePendingRequest (false);
687 if (Interlocked.CompareExchange (ref timeout_possible, 0, 0) == 0) {
689 timer.Change(2000, 0);
694 thread.Abort (new StepTimeout ());
697 internal void StartTimeoutTimer() {
698 thread = Thread.CurrentThread;
699 timer = new Timer (TimeoutReached, null, (int)ConfigTimeout.TotalMilliseconds, Timeout.Infinite);
702 internal void StopTimeoutTimer() {
709 internal bool TimeoutPossible {
710 get { return (Interlocked.CompareExchange (ref timeout_possible, 1, 1) == 1); }
713 internal void BeginTimeoutPossible ()
715 timeout_possible = 1;
718 internal void EndTimeoutPossible ()
720 Interlocked.CompareExchange (ref timeout_possible, 0, 1);