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;
77 const string app_global_res_key = "HttpContext.app_global_res_key";
78 internal static Assembly AppGlobalResourcesAssembly {
79 get { return (Assembly) AppDomain.CurrentDomain.GetData (app_global_res_key); }
80 set { AppDomain.CurrentDomain.SetData (app_global_res_key, value); }
83 internal static Assembly AppGlobalResourcesAssembly;
85 ProfileBase profile = null;
86 LinkedList<IHttpHandler> handlers;
89 public HttpContext (HttpWorkerRequest wr)
92 request = new HttpRequest (WorkerRequest, this);
93 response = new HttpResponse (WorkerRequest, this);
96 public HttpContext (HttpRequest request, HttpResponse response)
98 this.request = request;
99 this.response = response;
103 public Exception [] AllErrors {
108 if (errors is Exception){
109 Exception [] all = new Exception [1];
110 all [0] = (Exception) errors;
113 return (Exception []) (((ArrayList) errors).ToArray (typeof (Exception)));
117 public HttpApplicationState Application {
119 return HttpApplicationFactory.ApplicationState;
123 public HttpApplication ApplicationInstance {
129 app_instance = value;
136 return HttpRuntime.Cache;
141 // The "Current" property is set just after we have constructed it with
142 // the 'HttpContext (HttpWorkerRequest)' constructor.
144 #if !TARGET_JVM // No remoting CallContext support in Grasshopper
145 public static HttpContext Current {
147 return (HttpContext) CallContext.GetData ("c");
151 CallContext.SetData ("c", value);
156 public Exception Error {
158 if (errors == null || (errors is Exception))
159 return (Exception) errors;
160 return (Exception) (((ArrayList) errors) [0]);
164 public IHttpHandler Handler {
174 public bool IsCustomErrorEnabled {
177 CustomErrorsSection cfg = WebConfigurationManager.SafeGetSection ("system.web/customErrors", typeof (CustomErrorsSection)) as CustomErrorsSection;
179 CustomErrorsConfig cfg = null;
181 cfg = (CustomErrorsConfig) GetConfig ("system.web/customErrors");
189 if (cfg.Mode == CustomErrorMode.On)
192 return (cfg.Mode == CustomErrorMode.RemoteOnly) &&
193 (Request.WorkerRequest.GetLocalAddress () != Request.UserHostAddress);
197 public bool IsDebuggingEnabled {
200 CompilationSection section = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
201 return section.Debug;
204 return CompilationConfiguration.GetInstance (this).Debug;
212 public IDictionary Items {
215 items = new Hashtable ();
220 public HttpRequest Request {
226 public HttpResponse Response {
232 public HttpServerUtility Server {
235 server = new HttpServerUtility (this);
240 public HttpSessionState Session {
242 return session_state;
246 public bool SkipAuthorization {
248 return skip_authorization;
251 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
253 skip_authorization = value;
257 public DateTime Timestamp {
259 return time_stamp.ToLocalTime ();
263 public TraceContext Trace {
265 if (trace_context == null)
266 trace_context = new TraceContext (this);
267 return trace_context;
271 public IPrincipal User {
276 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
283 internal void PushHandler (IHttpHandler handler)
287 if (handlers == null)
288 handlers = new LinkedList <IHttpHandler> ();
289 handlers.AddLast (handler);
292 internal void PopHandler ()
294 if (handlers == null || handlers.Count == 0)
296 handlers.RemoveLast ();
299 IHttpHandler GetCurrentHandler ()
301 if (handlers == null || handlers.Count == 0)
304 return handlers.Last.Value;
307 IHttpHandler GetPreviousHandler ()
309 if (handlers == null || handlers.Count <= 1)
311 LinkedListNode <IHttpHandler> previous = handlers.Last.Previous;
312 if (previous != null)
313 return previous.Value;
317 public IHttpHandler CurrentHandler {
318 get { return GetCurrentHandler (); }
321 public IHttpHandler PreviousHandler {
322 get { return GetPreviousHandler (); }
325 public ProfileBase Profile {
327 if (profile == null) {
328 if (Request.IsAuthenticated)
329 profile = ProfileBase.Create (User.Identity.Name);
331 profile = ProfileBase.Create (Request.AnonymousID, false);
342 public void AddError (Exception errorInfo)
349 if (errors is Exception){
350 l = new ArrayList ();
354 l = (ArrayList) errors;
358 internal void ClearError (Exception e)
364 public void ClearError ()
370 [Obsolete ("use WebConfigurationManager.GetWebApplicationSection")]
372 public static object GetAppConfig (string name)
374 object o = ConfigurationSettings.GetConfig (name);
380 [Obsolete ("see GetSection")]
382 public object GetConfig (string name)
385 return GetSection (name);
387 return WebConfigurationSettings.GetConfig (name, this);
392 static object GetResourceObject (string classKey, string resourceKey, CultureInfo culture, Assembly assembly)
396 rm = new ResourceManager (classKey, assembly);
397 rm.IgnoreCase = true;
398 return rm.GetObject (resourceKey, culture);
399 } catch (MissingManifestResourceException) {
401 } catch (Exception ex) {
402 throw new HttpException ("Failed to retrieve the specified global resource object.", ex);
406 public static object GetGlobalResourceObject (string classKey, string resourceKey)
408 return GetGlobalResourceObject (classKey, resourceKey, Thread.CurrentThread.CurrentUICulture);
411 public static object GetGlobalResourceObject (string classKey, string resourceKey, CultureInfo culture)
413 if (AppGlobalResourcesAssembly == null)
414 throw new MissingManifestResourceException ();
415 return GetResourceObject ("Resources." + classKey, resourceKey, culture, AppGlobalResourcesAssembly);
418 public static object GetLocalResourceObject (string virtualPath, string resourceKey)
420 return GetLocalResourceObject (virtualPath, resourceKey, Thread.CurrentThread.CurrentUICulture);
423 public static object GetLocalResourceObject (string virtualPath, string resourceKey, CultureInfo culture)
425 if (!VirtualPathUtility.IsAbsolute (virtualPath))
426 throw new ArgumentException ("The specified virtualPath was not rooted.");
428 string path = Path.GetDirectoryName (virtualPath);
429 Assembly asm = AppResourcesCompiler.GetCachedLocalResourcesAssembly (path);
431 AppResourcesCompiler ac = new AppResourcesCompiler (path);
434 throw new MissingManifestResourceException ("A resource object was not found at the specified virtualPath.");
437 path = Path.GetFileName (virtualPath);
438 return GetResourceObject (path, resourceKey, culture, asm);
441 public object GetSection (string name)
443 return WebConfigurationManager.GetSection (name);
446 object IServiceProvider.GetService (Type service)
448 if (service == typeof (HttpWorkerRequest))
449 return WorkerRequest;
452 // We return everything out of properties in case
453 // they are dynamically computed in some form in the future.
455 if (service == typeof (HttpApplication))
456 return ApplicationInstance;
458 if (service == typeof (HttpRequest))
461 if (service == typeof (HttpResponse))
464 if (service == typeof (HttpSessionState))
467 if (service == typeof (HttpApplicationState))
470 if (service == typeof (IPrincipal))
473 if (service == typeof (Cache))
476 if (service == typeof (HttpContext))
479 if (service == typeof (IHttpHandler))
482 if (service == typeof (HttpServerUtility))
485 if (service == typeof (TraceContext))
491 public void RewritePath (string path)
494 RewritePath (path, true);
496 RewritePath (path, false);
500 public void RewritePath (string filePath, string pathInfo, string queryString)
502 RewritePath (filePath, pathInfo, queryString, false);
510 void RewritePath (string path, bool rebaseClientPath)
512 int qmark = path.IndexOf ('?');
514 RewritePath (path.Substring (0, qmark), "", path.Substring (qmark + 1), rebaseClientPath);
516 RewritePath (path, null, null, rebaseClientPath);
524 void RewritePath (string filePath, string pathInfo, string queryString, bool setClientFilePath)
526 filePath = UrlUtils.Combine (Request.BaseVirtualDir, filePath);
527 if (!StrUtils.StartsWith (filePath, HttpRuntime.AppDomainAppVirtualPath))
528 throw new HttpException (404, "The virtual path '" + filePath +
529 "' maps to another application.");
531 Request.SetCurrentExePath (filePath);
532 // A null pathInfo or queryString is ignored and previous values remain untouched
533 if (pathInfo != null)
534 Request.SetPathInfo (pathInfo);
536 if (queryString != null)
537 Request.QueryStringRaw = queryString;
539 if (setClientFilePath)
540 Request.SetFilePath (filePath);
546 internal void SetSession (HttpSessionState state)
548 session_state = state;
551 // URL of a page used for error redirection.
552 internal string ErrorPage {
562 internal TimeSpan ConfigTimeout {
564 if (config_timeout == null) {
566 HttpRuntimeSection section = (HttpRuntimeSection)WebConfigurationManager.GetSection ("system.web/httpRuntime");
567 config_timeout = section.ExecutionTimeout;
569 HttpRuntimeConfig config = (HttpRuntimeConfig)
570 GetConfig ("system.web/httpRuntime");
571 config_timeout = new TimeSpan (0, 0, config.ExecutionTimeout);
575 return (TimeSpan) config_timeout;
579 config_timeout = value;
584 internal bool CheckIfTimeout (DateTime t)
586 if (Interlocked.CompareExchange (ref timeout_possible, 0, 0) == 0)
589 TimeSpan ts = t - time_stamp;
590 return (ts > ConfigTimeout);
593 internal bool TimeoutPossible {
594 get { return (Interlocked.CompareExchange (ref timeout_possible, 1, 1) == 1); }
597 internal void BeginTimeoutPossible ()
599 timeout_possible = 1;
602 internal void EndTimeoutPossible ()
604 Interlocked.CompareExchange (ref timeout_possible, 0, 1);
612 internal Page LastPage {