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 {
56 // CAS - no InheritanceDemand here as the class is sealed
57 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
58 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;
76 internal static Assembly AppGlobalResourcesAssembly;
77 ProfileBase profile = null;
78 LinkedList<IHttpHandler> handlers;
81 public HttpContext (HttpWorkerRequest wr)
84 request = new HttpRequest (WorkerRequest, this);
85 response = new HttpResponse (WorkerRequest, this);
88 public HttpContext (HttpRequest request, HttpResponse response)
90 this.request = request;
91 this.response = response;
95 public Exception [] AllErrors {
100 if (errors is Exception){
101 Exception [] all = new Exception [1];
102 all [0] = (Exception) errors;
105 return (Exception []) (((ArrayList) errors).ToArray (typeof (Exception)));
109 public HttpApplicationState Application {
111 return HttpApplicationFactory.ApplicationState;
115 public HttpApplication ApplicationInstance {
121 app_instance = value;
128 return HttpRuntime.Cache;
133 // The "Current" property is set just after we have constructed it with
134 // the 'HttpContext (HttpWorkerRequest)' constructor.
136 #if !TARGET_JVM // No remoting CallContext support in Grasshopper
137 public static HttpContext Current {
139 return (HttpContext) CallContext.GetData ("c");
143 CallContext.SetData ("c", value);
148 public Exception Error {
150 if (errors == null || (errors is Exception))
151 return (Exception) errors;
152 return (Exception) (((ArrayList) errors) [0]);
156 public IHttpHandler Handler {
166 public bool IsCustomErrorEnabled {
169 CustomErrorsSection cfg = (CustomErrorsSection) WebConfigurationManager.GetSection ("system.web/customErrors");
171 CustomErrorsConfig cfg = null;
173 cfg = (CustomErrorsConfig) GetConfig ("system.web/customErrors");
181 if (cfg.Mode == CustomErrorMode.On)
184 return (cfg.Mode == CustomErrorMode.RemoteOnly) &&
185 (Request.WorkerRequest.GetLocalAddress () != Request.UserHostAddress);
189 public bool IsDebuggingEnabled {
192 CompilationSection section = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
193 return section.Debug;
196 return CompilationConfiguration.GetInstance (this).Debug;
204 public IDictionary Items {
207 items = new Hashtable ();
212 public HttpRequest Request {
218 public HttpResponse Response {
224 public HttpServerUtility Server {
227 server = new HttpServerUtility (this);
232 public HttpSessionState Session {
234 return session_state;
238 public bool SkipAuthorization {
240 return skip_authorization;
243 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
245 skip_authorization = value;
249 public DateTime Timestamp {
251 return time_stamp.ToLocalTime ();
255 public TraceContext Trace {
257 if (trace_context == null)
258 trace_context = new TraceContext (this);
259 return trace_context;
263 public IPrincipal User {
268 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
275 internal void PushHandler (IHttpHandler handler)
279 if (handlers == null)
280 handlers = new LinkedList <IHttpHandler> ();
281 handlers.AddLast (handler);
284 internal void PopHandler ()
286 if (handlers == null || handlers.Count == 0)
288 handlers.RemoveLast ();
291 IHttpHandler GetCurrentHandler ()
293 if (handlers == null || handlers.Count == 0)
296 return handlers.Last.Value;
299 IHttpHandler GetPreviousHandler ()
301 if (handlers == null || handlers.Count <= 1)
303 LinkedListNode <IHttpHandler> previous = handlers.Last.Previous;
304 if (previous != null)
305 return previous.Value;
309 public IHttpHandler CurrentHandler {
310 get { return GetCurrentHandler (); }
313 public IHttpHandler PreviousHandler {
314 get { return GetPreviousHandler (); }
317 public ProfileBase Profile {
319 if (profile == null) {
320 if (Request.IsAuthenticated)
321 profile = ProfileBase.Create (User.Identity.Name);
323 profile = ProfileBase.Create (Request.AnonymousID, false);
334 public void AddError (Exception errorInfo)
341 if (errors is Exception){
342 l = new ArrayList ();
346 l = (ArrayList) errors;
350 internal void ClearError (Exception e)
356 public void ClearError ()
362 [Obsolete ("use WebConfigurationManager.GetWebApplicationSection")]
364 public static object GetAppConfig (string name)
366 object o = ConfigurationSettings.GetConfig (name);
372 [Obsolete ("see GetSection")]
374 public object GetConfig (string name)
377 return GetSection (name);
379 return WebConfigurationSettings.GetConfig (name, this);
384 static object GetResourceObject (string classKey, string resourceKey, CultureInfo culture, Assembly assembly)
388 rm = new ResourceManager (classKey, assembly);
389 return rm.GetObject (resourceKey, culture);
390 } catch (MissingManifestResourceException) {
392 } catch (Exception ex) {
393 throw new HttpException ("Failed to retrieve the specified global resource object.", ex);
397 public static object GetGlobalResourceObject (string classKey, string resourceKey)
399 return GetGlobalResourceObject (classKey, resourceKey, Thread.CurrentThread.CurrentUICulture);
402 public static object GetGlobalResourceObject (string classKey, string resourceKey, CultureInfo culture)
404 if (AppGlobalResourcesAssembly == null)
405 throw new MissingManifestResourceException ();
406 return GetResourceObject ("Resources." + classKey, resourceKey, culture, AppGlobalResourcesAssembly);
409 public static object GetLocalResourceObject (string virtualPath, string resourceKey)
411 return GetLocalResourceObject (virtualPath, resourceKey, Thread.CurrentThread.CurrentUICulture);
414 public static object GetLocalResourceObject (string virtualPath, string resourceKey, CultureInfo culture)
416 if (!VirtualPathUtility.IsAbsolute (virtualPath))
417 throw new ArgumentException ("The specified virtualPath was not rooted.");
419 string path = Path.GetDirectoryName (virtualPath);
420 Assembly asm = AppResourcesCompiler.GetCachedLocalResourcesAssembly (path);
422 AppResourcesCompiler ac = new AppResourcesCompiler (path);
425 throw new MissingManifestResourceException ("A resource object was not found at the specified virtualPath.");
428 path = Path.GetFileName (virtualPath);
429 return GetResourceObject ("Resources." + path, resourceKey, culture, asm);
432 public object GetSection (string name)
434 return WebConfigurationManager.GetSection (name);
437 object IServiceProvider.GetService (Type service)
439 if (service == typeof (HttpWorkerRequest))
440 return WorkerRequest;
443 // We return everything out of properties in case
444 // they are dynamically computed in some form in the future.
446 if (service == typeof (HttpApplication))
447 return ApplicationInstance;
449 if (service == typeof (HttpRequest))
452 if (service == typeof (HttpResponse))
455 if (service == typeof (HttpSessionState))
458 if (service == typeof (HttpApplicationState))
461 if (service == typeof (IPrincipal))
464 if (service == typeof (Cache))
467 if (service == typeof (HttpContext))
470 if (service == typeof (IHttpHandler))
473 if (service == typeof (HttpServerUtility))
476 if (service == typeof (TraceContext))
482 public void RewritePath (string path)
485 RewritePath (path, true);
487 RewritePath (path, false);
491 public void RewritePath (string filePath, string pathInfo, string queryString)
493 RewritePath (filePath, pathInfo, queryString, false);
501 void RewritePath (string path, bool rebaseClientPath)
503 int qmark = path.IndexOf ('?');
505 RewritePath (path.Substring (0, qmark), "", path.Substring (qmark + 1), rebaseClientPath);
507 RewritePath (path, null, null, rebaseClientPath);
515 void RewritePath (string filePath, string pathInfo, string queryString, bool setClientFilePath)
517 filePath = UrlUtils.Combine (Request.BaseVirtualDir, filePath);
518 if (!filePath.StartsWith (HttpRuntime.AppDomainAppVirtualPath))
519 throw new HttpException (404, "The virtual path '" + filePath +
520 "' maps to another application.");
522 Request.SetCurrentExePath (filePath);
523 // A null pathInfo or queryString is ignored and previous values remain untouched
524 if (pathInfo != null)
525 Request.SetPathInfo (pathInfo);
527 if (queryString != null)
528 Request.QueryStringRaw = queryString;
530 if (setClientFilePath)
531 Request.SetFilePath (filePath);
537 internal void SetSession (HttpSessionState state)
539 session_state = state;
542 // URL of a page used for error redirection.
543 internal string ErrorPage {
553 internal TimeSpan ConfigTimeout {
555 if (config_timeout == null) {
557 HttpRuntimeSection section = (HttpRuntimeSection)WebConfigurationManager.GetSection ("system.web/httpRuntime");
558 config_timeout = section.ExecutionTimeout;
560 HttpRuntimeConfig config = (HttpRuntimeConfig)
561 GetConfig ("system.web/httpRuntime");
562 config_timeout = new TimeSpan (0, 0, config.ExecutionTimeout);
566 return (TimeSpan) config_timeout;
570 config_timeout = value;
574 internal bool CheckIfTimeout (DateTime t)
576 if (Interlocked.CompareExchange (ref timeout_possible, 0, 0) == 0)
579 TimeSpan ts = t - time_stamp;
580 return (ts > ConfigTimeout);
583 internal bool TimeoutPossible {
584 get { return (Interlocked.CompareExchange (ref timeout_possible, 1, 1) == 1); }
587 internal void BeginTimeoutPossible ()
589 timeout_possible = 1;
592 internal void EndTimeoutPossible ()
594 Interlocked.CompareExchange (ref timeout_possible, 0, 1);
601 internal Page LastPage {