2 // System.Web.HttpResponse.cs
6 // Miguel de Icaza (miguel@novell.com)
7 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
9 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections;
34 using System.Collections.Specialized;
36 using System.Web.Caching;
37 using System.Threading;
38 using System.Web.Util;
39 using System.Web.Configuration;
40 using System.Globalization;
41 using System.Security.Permissions;
42 using System.Web.Hosting;
43 using System.Web.SessionState;
45 namespace System.Web {
47 // CAS - no InheritanceDemand here as the class is sealed
48 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
49 public sealed partial class HttpResponse {
50 internal HttpWorkerRequest WorkerRequest;
51 internal HttpResponseStream output_stream;
52 internal bool buffer = true;
54 ArrayList fileDependencies;
58 HttpCachePolicy cache_policy;
60 HttpCookieCollection cookies;
62 int status_code = 200;
63 string status_description = "OK";
65 string content_type = "text/html";
68 CachedRawResponse cached_response;
69 string user_cache_control = "private";
70 string redirect_location;
72 static UnknownResponseHeader version_header;
75 // Negative Content-Length means we auto-compute the size of content-length
76 // can be overwritten with AppendHeader ("Content-Length", value)
78 long content_length = -1;
81 // The list of the headers that we will send back to the client, except
82 // the headers that we compute here.
84 ArrayList headers = new ArrayList ();
86 ArrayList cached_headers;
89 // Transfer encoding state
91 string transfer_encoding;
92 internal bool use_chunked;
95 internal bool suppress_content;
103 bool is_request_being_redirected;
104 Encoding headerEncoding;
107 static HttpResponse ()
110 HttpRuntimeSection config = WebConfigurationManager.GetSection ("system.web/httpRuntime") as HttpRuntimeSection;
112 HttpRuntimeConfig config = HttpContext.GetAppConfig ("system.web/httpRuntime") as HttpRuntimeConfig;
114 if (config.EnableVersionHeader) {
115 string version = Environment.Version.ToString (3);
116 version_header = new UnknownResponseHeader ("X-AspNet-Version", version);
120 internal HttpResponse ()
122 output_stream = new HttpResponseStream (this);
125 public HttpResponse (TextWriter writer) : this ()
127 this.writer = writer;
130 internal HttpResponse (HttpWorkerRequest worker_request, HttpContext context) : this ()
132 WorkerRequest = worker_request;
133 this.context = context;
136 if (worker_request != null)
137 use_chunked = (worker_request.GetHttpVersion () == "HTTP/1.1");
141 internal TextWriter SetTextWriter (TextWriter writer)
143 TextWriter prev = this.writer;
144 this.writer = writer;
148 internal string[] FileDependencies {
150 if (fileDependencies == null || fileDependencies.Count == 0)
151 return new string[0] {};
152 return (string[]) fileDependencies.ToArray (typeof (string));
156 ArrayList FileDependenciesArray {
158 if (fileDependencies == null)
159 fileDependencies = new ArrayList ();
160 return fileDependencies;
174 public bool BufferOutput {
185 // Use the default from <globalization> section if the client has not set the encoding
187 public Encoding ContentEncoding {
189 if (encoding == null) {
190 if (context != null) {
191 string client_content_type = context.Request.ContentType;
192 string parameter = HttpRequest.GetParameter (client_content_type, "; charset=");
193 if (parameter != null) {
195 // Do what the #1 web server does
196 encoding = Encoding.GetEncoding (parameter);
201 if (encoding == null)
202 encoding = WebEncoding.ResponseEncoding;
209 throw new ArgumentException ("ContentEncoding can not be null");
212 HttpWriter http_writer = writer as HttpWriter;
213 if (http_writer != null)
214 http_writer.SetEncoding (encoding);
218 public string ContentType {
224 content_type = value;
228 public string Charset {
231 charset = ContentEncoding.WebName;
242 public HttpCookieCollection Cookies {
245 cookies = new HttpCookieCollection (true, false);
252 if (cache_policy == null)
255 return cache_policy.ExpireMinutes ();
259 Cache.SetExpires (DateTime.Now + new TimeSpan (0, value, 0));
263 public DateTime ExpiresAbsolute {
265 return Cache.Expires;
269 Cache.SetExpires (value);
273 public Stream Filter {
275 if (WorkerRequest == null)
278 return output_stream.Filter;
282 output_stream.Filter = value;
286 public Encoding HeaderEncoding {
288 if (headerEncoding == null) {
289 GlobalizationSection gs = WebConfigurationManager.SafeGetSection ("system.web/globalization", typeof (GlobalizationSection)) as GlobalizationSection;
292 headerEncoding = Encoding.UTF8;
294 headerEncoding = gs.ResponseHeaderEncoding;
295 if (headerEncoding == Encoding.Unicode)
296 throw new HttpException ("HeaderEncoding must not be Unicode");
299 return headerEncoding;
303 throw new HttpException ("headers have already been sent");
305 throw new ArgumentNullException ("HeaderEncoding");
306 if (value == Encoding.Unicode)
307 throw new HttpException ("HeaderEncoding must not be Unicode");
308 headerEncoding = value;
312 public bool IsClientConnected {
314 if (WorkerRequest == null)
315 return true; // yep that's true
317 return WorkerRequest.IsClientConnected ();
321 public bool IsRequestBeingRedirected {
322 get { return is_request_being_redirected; }
325 public TextWriter Output {
328 writer = new HttpWriter (this);
334 public Stream OutputStream {
336 return output_stream;
340 public string RedirectLocation {
342 return redirect_location;
346 redirect_location = value;
350 public string Status {
351 get { return String.Concat (status_code.ToString (), " ", StatusDescription); }
354 int p = value.IndexOf (' ');
356 throw new HttpException ("Invalid format for the Status property");
358 string s = value.Substring (0, p);
361 if (!Int32.TryParse (s, out status_code))
362 throw new HttpException ("Invalid format for the Status property");
366 status_code = Int32.Parse (s);
368 throw new HttpException ("Invalid format for the Status property");
372 status_description = value.Substring (p+1);
376 public int StatusCode {
383 throw new HttpException ("headers have already been sent");
386 status_description = null;
390 public string StatusDescription {
392 if (status_description == null)
393 status_description = HttpWorkerRequest.GetStatusDescription (status_code);
395 return status_description;
400 throw new HttpException ("headers have already been sent");
402 status_description = value;
406 public bool SuppressContent {
408 return suppress_content;
412 suppress_content = value;
417 [MonoTODO ("Not implemented")]
418 public void AddCacheDependency (CacheDependency[] dependencies)
420 throw new NotImplementedException ();
423 [MonoTODO ("Not implemented")]
424 public void AddCacheItemDependencies (string[] cacheKeys)
426 throw new NotImplementedException ();
429 [MonoTODO("Currently does nothing")]
430 public void AddCacheItemDependencies (ArrayList cacheKeys)
432 // TODO: talk to jackson about the cache
435 [MonoTODO("Currently does nothing")]
436 public void AddCacheItemDependency (string cacheKey)
438 // TODO: talk to jackson about the cache
441 public void AddFileDependencies (ArrayList filenames)
443 if (filenames == null || filenames.Count == 0)
445 FileDependenciesArray.AddRange (filenames);
448 public void AddFileDependencies (string[] filenames)
450 if (filenames == null || filenames.Length == 0)
452 FileDependenciesArray.AddRange (filenames);
456 public void AddFileDependency (string filename)
458 if (filename == null || filename == String.Empty)
460 FileDependenciesArray.Add (filename);
463 public void AddHeader (string name, string value)
465 AppendHeader (name, value);
468 public void AppendCookie (HttpCookie cookie)
470 Cookies.Add (cookie);
475 // Special case for Content-Length, Content-Type, Transfer-Encoding and Cache-Control
478 public void AppendHeader (string name, string value)
481 throw new HttpException ("headers have been already sent");
484 if (String.Compare (name, "content-length", true, CultureInfo.InvariantCulture) == 0){
485 content_length = (long) UInt64.Parse (value);
491 if (String.Compare (name, "content-type", true, CultureInfo.InvariantCulture) == 0){
497 if (String.Compare (name, "transfer-encoding", true, CultureInfo.InvariantCulture) == 0){
498 transfer_encoding = value;
504 if (String.Compare (name, "cache-control", true, CultureInfo.InvariantCulture) == 0){
505 user_cache_control = value;
509 headers.Add (new UnknownResponseHeader (name, value));
512 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
513 public void AppendToLog (string param)
515 Console.Write ("System.Web: ");
516 Console.WriteLine (param);
519 public string ApplyAppPathModifier (string virtualPath)
521 if (virtualPath == null)
524 if (virtualPath == "")
525 return context.Request.RootVirtualDir;
527 if (UrlUtils.IsRelativeUrl (virtualPath)) {
528 virtualPath = UrlUtils.Combine (context.Request.RootVirtualDir, virtualPath);
529 } else if (UrlUtils.IsRooted (virtualPath)) {
530 virtualPath = UrlUtils.Canonic (virtualPath);
533 bool cookieless = false;
535 SessionStateSection config = WebConfigurationManager.GetSection ("system.web/sessionState") as SessionStateSection;
536 cookieless = SessionStateModule.IsCookieLess (context, config);
538 SessionConfig config = HttpContext.GetAppConfig ("system.web/sessionState") as SessionConfig;
539 cookieless = config.CookieLess;
544 if (app_path_mod != null && virtualPath.IndexOf (app_path_mod) < 0) {
545 if (UrlUtils.HasSessionId (virtualPath))
546 virtualPath = UrlUtils.RemoveSessionId (VirtualPathUtility.GetDirectory (virtualPath), virtualPath);
547 return UrlUtils.InsertSessionId (app_path_mod, virtualPath);
553 public void BinaryWrite (byte [] buffer)
555 output_stream.Write (buffer, 0, buffer.Length);
558 internal void BinaryWrite (byte [] buffer, int start, int len)
560 output_stream.Write (buffer, start, len);
568 public void ClearContent ()
570 output_stream.Clear ();
574 public void ClearHeaders ()
577 throw new HttpException ("headers have been already sent");
579 // Reset the special case headers.
581 content_type = "text/html";
582 transfer_encoding = null;
583 user_cache_control = null;
587 internal bool HeadersSent {
597 if (WorkerRequest != null)
598 WorkerRequest.CloseConnection ();
607 if (context.TimeoutPossible) {
608 Thread.CurrentThread.Abort (FlagEnd.Value);
610 // If this is called from an async event, signal the completion
612 HttpApplication app_instance = context.ApplicationInstance;
613 if (app_instance != null)
614 app_instance.CompleteRequest ();
621 // Transfer-Encoding (chunked)
624 void AddHeadersNoCache (ArrayList write_headers, bool final_flush)
631 write_headers.Add (new UnknownResponseHeader ("Transfer-Encoding", "chunked"));
632 else if (transfer_encoding != null)
633 write_headers.Add (new UnknownResponseHeader ("Transfer-Encoding", transfer_encoding));
635 if (redirect_location != null)
636 write_headers.Add (new UnknownResponseHeader ("Location", redirect_location));
639 if (version_header != null)
640 write_headers.Add (version_header);
643 // If Content-Length is set.
645 if (content_length >= 0) {
646 write_headers.Add (new KnownResponseHeader (HttpWorkerRequest.HeaderContentLength,
647 content_length.ToString (CultureInfo.InvariantCulture)));
648 } else if (BufferOutput) {
651 // If we are buffering and this is the last flush, not a middle-flush,
652 // we know the content-length.
654 content_length = output_stream.total;
655 write_headers.Add (new KnownResponseHeader (HttpWorkerRequest.HeaderContentLength,
656 content_length.ToString (CultureInfo.InvariantCulture)));
659 // We are buffering, and this is a flush in the middle.
660 // If we are not chunked, we need to set "Connection: close".
663 write_headers.Add (new KnownResponseHeader (HttpWorkerRequest.HeaderConnection, "close"));
668 // If the content-length is not set, and we are not buffering, we must
672 write_headers.Add (new KnownResponseHeader (HttpWorkerRequest.HeaderConnection, "close"));
678 // Cache Control, the cache policy takes precedence over the cache_control property.
680 if (cache_policy != null)
681 cache_policy.SetHeaders (this, headers);
683 write_headers.Add (new UnknownResponseHeader ("Cache-Control", CacheControl));
688 if (content_type != null){
689 string header = content_type;
691 if (charset_set || header == "text/plain" || header == "text/html") {
692 if (header.IndexOf ("charset=") == -1) {
693 if (charset == null || charset == "")
694 charset = ContentEncoding.HeaderName;
695 header += "; charset=" + charset;
699 write_headers.Add (new UnknownResponseHeader ("Content-Type", header));
702 if (cookies != null && cookies.Count != 0){
703 int n = cookies.Count;
704 for (int i = 0; i < n; i++)
705 write_headers.Add (cookies.Get (i).GetCookieHeader ());
707 // For J2EE Portal support emulate cookies by storing them in the session.
708 context.Request.SetSessionCookiesForPortal (cookies);
713 internal void WriteHeaders (bool final_flush)
721 if (context != null) {
722 HttpApplication app_instance = context.ApplicationInstance;
723 if (app_instance != null)
724 app_instance.TriggerPreSendRequestHeaders ();
729 if (cached_response != null)
730 cached_response.SetHeaders (headers);
732 // If this page is cached use the cached headers
733 // instead of the standard headers
734 ArrayList write_headers = headers;
735 if (cached_headers != null)
736 write_headers = cached_headers;
738 AddHeadersNoCache (write_headers, final_flush);
740 if (WorkerRequest != null)
741 WorkerRequest.SendStatus (status_code, StatusDescription);
743 if (WorkerRequest != null) {
744 foreach (BaseResponseHeader header in write_headers){
745 header.SendContent (WorkerRequest);
750 internal void DoFilter (bool close)
752 if (output_stream.HaveFilter && context != null && context.Error == null)
753 output_stream.ApplyFilter (close);
756 internal void Flush (bool final_flush)
758 DoFilter (final_flush);
760 if (final_flush || status_code != 200)
764 bool head = ((context != null) && (context.Request.HttpMethod == "HEAD"));
765 if (suppress_content || head) {
768 output_stream.Clear ();
769 if (WorkerRequest != null)
770 output_stream.Flush (WorkerRequest, true); // ignore final_flush here.
775 WriteHeaders (final_flush);
777 if (context != null) {
778 HttpApplication app_instance = context.ApplicationInstance;
779 if (app_instance != null)
780 app_instance.TriggerPreSendRequestContent ();
784 MemoryStream ms = output_stream.GetData ();
785 cached_response.ContentLength = (int) ms.Length;
786 cached_response.SetData (ms.GetBuffer ());
789 if (WorkerRequest != null)
790 output_stream.Flush (WorkerRequest, final_flush);
798 public void Pics (string value)
800 AppendHeader ("PICS-Label", value);
803 public void Redirect (string url)
805 Redirect (url, true);
808 public void Redirect (string url, bool endResponse)
811 throw new HttpException ("Headers have already been sent");
814 is_request_being_redirected = true;
820 url = ApplyAppPathModifier (url);
821 redirect_location = url;
823 // Text for browsers that can't handle location header
824 Write ("<html><head><title>Object moved</title></head><body>\r\n");
825 Write ("<h2>Object moved to <a href=\"" + url + "\">here</a></h2>\r\n");
826 Write ("</body><html>\r\n");
831 is_request_being_redirected = false;
835 public static void RemoveOutputCacheItem (string path)
838 throw new ArgumentNullException ("path");
840 if (path.Length == 0)
844 throw new ArgumentException ("'" + path + "' is not an absolute virtual path.");
846 HttpRuntime.InternalCache.Remove (path);
849 public void SetCookie (HttpCookie cookie)
851 AppendCookie (cookie);
854 public void Write (char ch)
859 public void Write (object obj)
864 Output.Write (obj.ToString ());
867 public void Write (string s)
872 public void Write (char [] buffer, int index, int count)
874 Output.Write (buffer, index, count);
877 internal void WriteFile (FileStream fs, long offset, long size)
879 byte [] buffer = new byte [32*1024];
882 fs.Position = offset;
886 while (remain > 0 && (n = fs.Read (buffer, 0, (int) Math.Min (remain, 32*1024))) != 0){
888 output_stream.Write (buffer, 0, n);
892 public void WriteFile (string filename)
894 WriteFile (filename, false);
897 public void WriteFile (string filename, bool readIntoMemory)
899 if (filename == null)
900 throw new ArgumentNullException ("filename");
903 using (FileStream fs = File.OpenRead (filename))
904 WriteFile (fs, 0, fs.Length);
906 FileInfo fi = new FileInfo (filename);
907 output_stream.WriteFile (filename, 0, fi.Length);
912 output_stream.ApplyFilter (false);
917 public void WriteFile (IntPtr fileHandle, long offset, long size) {
918 throw new PlatformNotSupportedException("IntPtr not supported");
921 public void WriteFile (IntPtr fileHandle, long offset, long size)
924 throw new ArgumentNullException ("offset can not be negative");
926 throw new ArgumentNullException ("size can not be negative");
931 // Note: this .ctor will throw a SecurityException if the caller
932 // doesn't have the UnmanagedCode permission
933 using (FileStream fs = new FileStream (fileHandle, FileAccess.Read))
934 WriteFile (fs, offset, size);
938 output_stream.ApplyFilter (false);
943 public void WriteFile (string filename, long offset, long size)
945 if (filename == null)
946 throw new ArgumentNullException ("filename");
948 throw new ArgumentNullException ("offset can not be negative");
950 throw new ArgumentNullException ("size can not be negative");
955 FileStream fs = File.OpenRead (filename);
956 WriteFile (fs, offset, size);
961 output_stream.ApplyFilter (false);
965 [MonoTODO ("Not implemented")]
966 public void WriteSubstitution (HttpResponseSubstitutionCallback callback)
968 throw new NotImplementedException ();
972 // Like WriteFile, but never buffers, so we manually Flush here
974 public void TransmitFile (string filename)
976 if (filename == null)
977 throw new ArgumentNullException ("filename");
979 TransmitFile (filename, false);
982 internal void TransmitFile (string filename, bool final_flush)
984 FileInfo fi = new FileInfo (filename);
985 using (Stream s = fi.OpenRead ()); // Just check if we can read.
986 output_stream.WriteFile (filename, 0, fi.Length);
987 output_stream.ApplyFilter (final_flush);
992 internal void TransmitFile (VirtualFile vf)
994 TransmitFile (vf, false);
997 internal void TransmitFile (VirtualFile vf, bool final_flush)
1000 throw new ArgumentNullException ("vf");
1002 using (Stream s = vf.Open ()) {
1003 long len = s.Length;
1004 byte[] buf = new byte [len];
1005 int readBytes = s.Read (buf, 0, (int) len);
1006 output_stream.Write (buf, 0, readBytes);
1007 output_stream.ApplyFilter (final_flush);
1008 Flush (final_flush);
1013 #region Session state support
1014 internal void SetAppPathModifier (string app_modifier)
1016 app_path_mod = app_modifier;
1020 #region Cache Support
1021 internal void SetCachedHeaders (ArrayList headers)
1023 cached_headers = headers;
1026 internal bool IsCached {
1027 get { return cached_response != null; }
1030 cached_response = new CachedRawResponse (cache_policy);
1032 cached_response = null;
1036 public HttpCachePolicy Cache {
1038 if (cache_policy == null)
1039 cache_policy = new HttpCachePolicy ();
1041 return cache_policy;
1045 internal CachedRawResponse GetCachedResponse ()
1047 if (cached_response != null) {
1048 cached_response.StatusCode = StatusCode;
1049 cached_response.StatusDescription = StatusDescription;
1052 return cached_response;
1056 // This is one of the old ASP compatibility methods, the real cache
1057 // control is in the Cache property, and this is a second class citizen
1059 public string CacheControl {
1061 if (value == null || value == "") {
1062 Cache.SetCacheability (HttpCacheability.NoCache);
1063 user_cache_control = null;
1064 } else if (String.Compare (value, "public", true, CultureInfo.InvariantCulture) == 0) {
1065 Cache.SetCacheability (HttpCacheability.Public);
1066 user_cache_control = "public";
1067 } else if (String.Compare (value, "private", true, CultureInfo.InvariantCulture) == 0) {
1068 Cache.SetCacheability (HttpCacheability.Private);
1069 user_cache_control = "private";
1070 } else if (String.Compare (value, "no-cache", true, CultureInfo.InvariantCulture) == 0) {
1071 Cache.SetCacheability (HttpCacheability.NoCache);
1072 user_cache_control = "no-cache";
1074 throw new ArgumentException ("CacheControl property only allows `public', " +
1075 "`private' or no-cache, for different uses, use " +
1076 "Response.AppendHeader");
1079 get { return (user_cache_control != null) ? user_cache_control : "private"; }
1083 internal int GetOutputByteCount ()
1085 return output_stream.GetTotalLength ();
1088 internal void ReleaseResources ()
1090 output_stream.ReleaseResources (true);
1091 output_stream = null;
1098 static class FlagEnd
1100 public static readonly object Value = new object ();