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);
115 public HttpContext (HttpRequest request, HttpResponse response)
117 this.request = request;
118 this.response = response;
122 internal bool IsProcessingInclude {
123 get { return _isProcessingInclude; }
124 set { _isProcessingInclude = value; }
127 public Exception [] AllErrors {
132 if (errors is Exception){
133 Exception [] all = new Exception [1];
134 all [0] = (Exception) errors;
137 return (Exception []) (((ArrayList) errors).ToArray (typeof (Exception)));
141 public HttpApplicationState Application {
143 return HttpApplicationFactory.ApplicationState;
147 public HttpApplication ApplicationInstance {
153 app_instance = value;
160 return HttpRuntime.Cache;
164 internal Cache InternalCache {
166 return HttpRuntime.InternalCache;
171 // The "Current" property is set just after we have constructed it with
172 // the 'HttpContext (HttpWorkerRequest)' constructor.
174 #if !TARGET_JVM // No remoting CallContext support in Grasshopper
175 public static HttpContext Current {
177 return (HttpContext) CallContext.GetData ("c");
181 CallContext.SetData ("c", value);
186 public Exception Error {
188 if (errors == null || (errors is Exception))
189 return (Exception) errors;
190 return (Exception) (((ArrayList) errors) [0]);
194 public IHttpHandler Handler {
204 public bool IsCustomErrorEnabled {
207 return IsCustomErrorEnabledUnsafe;
215 internal bool IsCustomErrorEnabledUnsafe {
217 CustomErrorsSection cfg = (CustomErrorsSection) WebConfigurationManager.GetSection ("system.web/customErrors");
218 if (cfg.Mode == CustomErrorMode.On)
221 return (cfg.Mode == CustomErrorMode.RemoteOnly) && !Request.IsLocal;
225 public bool IsDebuggingEnabled {
226 get { return HttpRuntime.IsDebuggingEnabled; }
229 public IDictionary Items {
232 items = new Hashtable ();
237 public HttpRequest Request {
243 public HttpResponse Response {
249 public HttpServerUtility Server {
252 server = new HttpServerUtility (this);
257 public HttpSessionState Session {
259 return session_state;
263 public bool SkipAuthorization {
265 return skip_authorization;
268 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
270 skip_authorization = value;
274 public DateTime Timestamp {
276 return time_stamp.ToLocalTime ();
280 public TraceContext Trace {
282 if (trace_context == null)
283 trace_context = new TraceContext (this);
284 return trace_context;
288 public IPrincipal User {
293 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
299 internal bool MapRequestHandlerDone {
304 // The two properties below are defined only when the IIS7 integrated mode is used.
305 // They are useless under Mono
306 public RequestNotification CurrentNotification {
307 get { throw new PlatformNotSupportedException ("This property is not supported on Mono."); }
310 public bool IsPostNotification {
311 get { throw new PlatformNotSupportedException ("This property is not supported on Mono."); }
314 internal void PushHandler (IHttpHandler handler)
318 if (handlers == null)
319 handlers = new LinkedList <IHttpHandler> ();
320 handlers.AddLast (handler);
323 internal void PopHandler ()
325 if (handlers == null || handlers.Count == 0)
327 handlers.RemoveLast ();
330 IHttpHandler GetCurrentHandler ()
332 if (handlers == null || handlers.Count == 0)
335 return handlers.Last.Value;
338 IHttpHandler GetPreviousHandler ()
340 if (handlers == null || handlers.Count <= 1)
342 LinkedListNode <IHttpHandler> previous = handlers.Last.Previous;
343 if (previous != null)
344 return previous.Value;
348 public IHttpHandler CurrentHandler {
349 get { return GetCurrentHandler (); }
352 public IHttpHandler PreviousHandler {
353 get { return GetPreviousHandler (); }
356 internal bool ProfileInitialized {
357 get { return profile != null; }
360 public ProfileBase Profile {
362 if (profile == null) {
363 if (Request.IsAuthenticated)
364 profile = ProfileBase.Create (User.Identity.Name);
366 profile = ProfileBase.Create (Request.AnonymousID, false);
376 public void AddError (Exception errorInfo)
383 if (errors is Exception){
384 l = new ArrayList ();
388 l = (ArrayList) errors;
392 internal void ClearError (Exception e)
398 internal bool HasError (Exception e)
403 return (errors is ArrayList) ?
404 ((ArrayList) errors).Contains (e) : false;
407 public void ClearError ()
412 [Obsolete ("use WebConfigurationManager.GetWebApplicationSection")]
413 public static object GetAppConfig (string name)
415 object o = ConfigurationSettings.GetConfig (name);
420 [Obsolete ("see GetSection")]
421 public object GetConfig (string name)
423 return GetSection (name);
426 public static object GetGlobalResourceObject (string classKey, string resourceKey)
428 return GetGlobalResourceObject (classKey, resourceKey, Thread.CurrentThread.CurrentUICulture);
431 static bool EnsureProviderFactory ()
433 if (resource_providers == null)
434 resource_providers = new Dictionary <string, IResourceProvider> ();
436 if (provider_factory != null)
439 GlobalizationSection gs = WebConfigurationManager.GetSection ("system.web/globalization") as GlobalizationSection;
444 String rsfTypeName = gs.ResourceProviderFactoryType;
445 bool usingDefault = false;
446 if (String.IsNullOrEmpty (rsfTypeName)) {
448 rsfTypeName = typeof (DefaultResourceProviderFactory).AssemblyQualifiedName;
451 Type rsfType = HttpApplication.LoadType (rsfTypeName, true);
452 ResourceProviderFactory rpf = Activator.CreateInstance (rsfType) as ResourceProviderFactory;
454 if (rpf == null && usingDefault)
457 provider_factory = rpf;
459 default_provider_factory = rpf as DefaultResourceProviderFactory;
464 internal static IResourceProvider GetResourceProvider (string virtualPath, bool isLocal)
466 if (!EnsureProviderFactory ())
469 // TODO: check if it makes sense to cache the providers and, if yes, maybe
470 // we should expire the entries (or just store them in InternalCache?)
471 IResourceProvider rp = null;
472 if (!resource_providers.TryGetValue (virtualPath, out rp)) {
474 HttpContext ctx = HttpContext.Current;
475 HttpRequest req = ctx != null ? ctx.Request : null;
476 rp = provider_factory.CreateLocalResourceProvider (virtualPath);
478 rp = provider_factory.CreateGlobalResourceProvider (virtualPath);
482 HttpContext ctx = HttpContext.Current;
483 HttpRequest req = ctx != null ? ctx.Request : null;
484 rp = DefaultProviderFactory.CreateLocalResourceProvider (virtualPath);
486 rp = DefaultProviderFactory.CreateGlobalResourceProvider (virtualPath);
492 resource_providers.Add (virtualPath, rp);
498 static object GetGlobalObjectFromFactory (string classKey, string resourceKey, CultureInfo culture)
500 // FIXME: Retention of data
501 IResourceProvider rp = GetResourceProvider (classKey, false);
505 return rp.GetObject (resourceKey, culture);
508 public static object GetGlobalResourceObject (string classKey, string resourceKey, CultureInfo culture)
510 return GetGlobalObjectFromFactory ("Resources." + classKey, resourceKey, culture);
513 public static object GetLocalResourceObject (string virtualPath, string resourceKey)
515 return GetLocalResourceObject (virtualPath, resourceKey, Thread.CurrentThread.CurrentUICulture);
518 static object GetLocalObjectFromFactory (string virtualPath, string resourceKey, CultureInfo culture)
520 IResourceProvider rp = GetResourceProvider (virtualPath, true);
524 return rp.GetObject (resourceKey, culture);
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 return GetLocalObjectFromFactory (virtualPath, resourceKey, culture);
535 public object GetSection (string name)
537 return WebConfigurationManager.GetSection (name);
540 object IServiceProvider.GetService (Type service)
542 if (service == typeof (HttpWorkerRequest))
543 return WorkerRequest;
546 // We return everything out of properties in case
547 // they are dynamically computed in some form in the future.
549 if (service == typeof (HttpApplication))
550 return ApplicationInstance;
552 if (service == typeof (HttpRequest))
555 if (service == typeof (HttpResponse))
558 if (service == typeof (HttpSessionState))
561 if (service == typeof (HttpApplicationState))
564 if (service == typeof (IPrincipal))
567 if (service == typeof (Cache))
570 if (service == typeof (HttpContext))
573 if (service == typeof (IHttpHandler))
576 if (service == typeof (HttpServerUtility))
579 if (service == typeof (TraceContext))
585 public void RemapHandler (IHttpHandler handler)
587 if (MapRequestHandlerDone)
588 throw new InvalidOperationException ("The RemapHandler method was called after the MapRequestHandler event occurred.");
592 public void RewritePath (string path)
594 RewritePath (path, true);
597 public void RewritePath (string filePath, string pathInfo, string queryString)
599 RewritePath (filePath, pathInfo, queryString, false);
602 public void RewritePath (string path, bool rebaseClientPath)
604 int qmark = path.IndexOf ('?');
606 RewritePath (path.Substring (0, qmark), String.Empty, path.Substring (qmark + 1), rebaseClientPath);
608 RewritePath (path, null, null, rebaseClientPath);
611 public void RewritePath (string filePath, string pathInfo, string queryString, bool setClientFilePath)
613 if (filePath == null)
614 throw new ArgumentNullException ("filePath");
615 if (!VirtualPathUtility.IsValidVirtualPath (filePath))
616 throw new HttpException ("'" + HttpUtility.HtmlEncode (filePath) + "' is not a valid virtual path.");
618 bool pathRelative = VirtualPathUtility.IsAppRelative (filePath);
619 bool pathAbsolute = pathRelative ? false : VirtualPathUtility.IsAbsolute (filePath);
620 HttpRequest req = Request;
624 if (pathRelative || pathAbsolute) {
626 filePath = VirtualPathUtility.ToAbsolute (filePath);
630 filePath = VirtualPathUtility.AppendTrailingSlash (req.BaseVirtualDir) + filePath;
632 if (!StrUtils.StartsWith (filePath, HttpRuntime.AppDomainAppVirtualPath))
633 throw new HttpException (404, "The virtual path '" + HttpUtility.HtmlEncode (filePath) + "' maps to another application.", filePath);
635 req.SetCurrentExePath (filePath);
636 req.SetFilePath (filePath);
638 if (setClientFilePath)
639 req.ClientFilePath = filePath;
641 // A null pathInfo or queryString is ignored and previous values remain untouched
642 if (pathInfo != null)
643 req.SetPathInfo (pathInfo);
645 if (queryString != null)
646 req.QueryStringRaw = queryString;
651 internal void SetSession (HttpSessionState state)
653 session_state = state;
656 // URL of a page used for error redirection.
657 internal string ErrorPage {
667 internal TimeSpan ConfigTimeout {
669 if (config_timeout == null) {
670 HttpRuntimeSection section = (HttpRuntimeSection)WebConfigurationManager.GetSection ("system.web/httpRuntime");
671 config_timeout = section.ExecutionTimeout;
674 return (TimeSpan) config_timeout;
678 config_timeout = value;
681 TimeSpan remaining = value - (DateTime.UtcNow - time_stamp);
682 long remaining_ms = Math.Max ((long)remaining.TotalMilliseconds, 0);
684 // See http://msdn2.microsoft.com/en-us/library/7hs7492w.aspx
685 if (remaining_ms > 4294967294)
686 remaining_ms = 4294967294;
688 timer.Change (remaining_ms, (long)Timeout.Infinite);
695 void TimeoutReached(object state) {
696 HttpRuntime.QueuePendingRequest (false);
697 if (Interlocked.CompareExchange (ref timeout_possible, 0, 0) == 0) {
698 timer.Change(2000, 0);
703 thread.Abort (new StepTimeout ());
706 internal void StartTimeoutTimer() {
707 thread = Thread.CurrentThread;
708 timer = new Timer (TimeoutReached, null, (int)ConfigTimeout.TotalMilliseconds, Timeout.Infinite);
711 internal void StopTimeoutTimer() {
718 internal bool TimeoutPossible {
719 get { return (Interlocked.CompareExchange (ref timeout_possible, 1, 1) == 1); }
722 internal void BeginTimeoutPossible ()
724 timeout_possible = 1;
727 internal void EndTimeoutPossible ()
729 Interlocked.CompareExchange (ref timeout_possible, 0, 1);