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;
43 namespace System.Web {
45 // CAS - no InheritanceDemand here as the class is sealed
46 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
47 public sealed partial class HttpResponse {
48 internal HttpWorkerRequest WorkerRequest;
49 internal HttpResponseStream output_stream;
50 internal bool buffer = true;
52 ArrayList fileDependencies;
56 HttpCachePolicy cache_policy;
58 HttpCookieCollection cookies;
60 int status_code = 200;
61 string status_description = "OK";
63 string content_type = "text/html";
66 CachedRawResponse cached_response;
67 string user_cache_control = "private";
68 string redirect_location;
71 // Negative Content-Length means we auto-compute the size of content-length
72 // can be overwritten with AppendHeader ("Content-Length", value)
74 long content_length = -1;
77 // The list of the headers that we will send back to the client, except
78 // the headers that we compute here.
80 ArrayList headers = new ArrayList ();
82 ArrayList cached_headers;
85 // Transfer encoding state
87 string transfer_encoding;
88 internal bool use_chunked;
91 internal bool suppress_content;
101 internal object FlagEnd = new object ();
104 bool is_request_being_redirected;
105 Encoding headerEncoding;
108 internal HttpResponse ()
110 output_stream = new HttpResponseStream (this);
113 public HttpResponse (TextWriter writer) : this ()
115 this.writer = writer;
118 internal HttpResponse (HttpWorkerRequest worker_request, HttpContext context) : this ()
120 WorkerRequest = worker_request;
121 this.context = context;
123 if (worker_request != null)
124 use_chunked = (worker_request.GetHttpVersion () == "HTTP/1.1");
127 internal TextWriter SetTextWriter (TextWriter writer)
129 TextWriter prev = this.writer;
130 this.writer = writer;
134 internal string[] FileDependencies {
136 if (fileDependencies == null || fileDependencies.Count == 0)
137 return new string[0] {};
138 return (string[]) fileDependencies.ToArray (typeof (string));
142 ArrayList FileDependenciesArray {
144 if (fileDependencies == null)
145 fileDependencies = new ArrayList ();
146 return fileDependencies;
160 public bool BufferOutput {
171 // Use the default from <globalization> section if the client has not set the encoding
173 public Encoding ContentEncoding {
175 if (encoding == null) {
176 if (context != null) {
177 string client_content_type = context.Request.ContentType;
178 string parameter = HttpRequest.GetParameter (client_content_type, "; charset=");
179 if (parameter != null) {
181 // Do what the #1 web server does
182 encoding = Encoding.GetEncoding (parameter);
187 if (encoding == null)
188 encoding = WebEncoding.ResponseEncoding;
195 throw new ArgumentException ("ContentEncoding can not be null");
198 HttpWriter http_writer = writer as HttpWriter;
199 if (http_writer != null)
200 http_writer.SetEncoding (encoding);
204 public string ContentType {
210 content_type = value;
214 public string Charset {
217 charset = ContentEncoding.WebName;
228 public HttpCookieCollection Cookies {
231 cookies = new HttpCookieCollection (true, false);
238 if (cache_policy == null)
241 return cache_policy.ExpireMinutes ();
245 Cache.SetExpires (DateTime.Now + new TimeSpan (0, value, 0));
249 public DateTime ExpiresAbsolute {
251 return Cache.Expires;
255 Cache.SetExpires (value);
259 public Stream Filter {
261 if (WorkerRequest == null)
264 return output_stream.Filter;
268 output_stream.Filter = value;
272 public Encoding HeaderEncoding {
274 if (headerEncoding == null) {
275 GlobalizationSection gs = WebConfigurationManager.SafeGetSection ("system.web/globalization", typeof (GlobalizationSection)) as GlobalizationSection;
278 headerEncoding = Encoding.UTF8;
280 headerEncoding = gs.ResponseHeaderEncoding;
281 if (headerEncoding == Encoding.Unicode)
282 throw new HttpException ("HeaderEncoding must not be Unicode");
285 return headerEncoding;
289 throw new HttpException ("headers have already been sent");
291 throw new ArgumentNullException ("HeaderEncoding");
292 if (value == Encoding.Unicode)
293 throw new HttpException ("HeaderEncoding must not be Unicode");
294 headerEncoding = value;
298 public bool IsClientConnected {
300 if (WorkerRequest == null)
301 return true; // yep that's true
303 return WorkerRequest.IsClientConnected ();
307 public bool IsRequestBeingRedirected {
308 get { return is_request_being_redirected; }
311 public TextWriter Output {
314 writer = new HttpWriter (this);
320 public Stream OutputStream {
322 return output_stream;
326 public string RedirectLocation {
328 return redirect_location;
332 redirect_location = value;
336 public string Status {
337 get { return String.Concat (status_code.ToString (), " ", StatusDescription); }
340 int p = value.IndexOf (' ');
342 throw new HttpException ("Invalid format for the Status property");
344 string s = value.Substring (0, p);
347 if (!Int32.TryParse (s, out status_code))
348 throw new HttpException ("Invalid format for the Status property");
352 status_code = Int32.Parse (s);
354 throw new HttpException ("Invalid format for the Status property");
358 status_description = value.Substring (p+1);
362 public int StatusCode {
369 throw new HttpException ("headers have already been sent");
372 status_description = null;
376 public string StatusDescription {
378 if (status_description == null)
379 status_description = HttpWorkerRequest.GetStatusDescription (status_code);
381 return status_description;
386 throw new HttpException ("headers have already been sent");
388 status_description = value;
392 public bool SuppressContent {
394 return suppress_content;
398 suppress_content = value;
403 [MonoTODO ("Not implemented")]
404 public void AddCacheDependency (CacheDependency[] dependencies)
406 throw new NotImplementedException ();
409 [MonoTODO ("Not implemented")]
410 public void AddCacheItemDependencies (string[] cacheKeys)
412 throw new NotImplementedException ();
415 [MonoTODO("Currently does nothing")]
416 public void AddCacheItemDependencies (ArrayList cacheKeys)
418 // TODO: talk to jackson about the cache
421 [MonoTODO("Currently does nothing")]
422 public void AddCacheItemDependency (string cacheKey)
424 // TODO: talk to jackson about the cache
427 public void AddFileDependencies (ArrayList filenames)
429 if (filenames == null || filenames.Count == 0)
431 FileDependenciesArray.AddRange (filenames);
434 public void AddFileDependencies (string[] filenames)
436 if (filenames == null || filenames.Length == 0)
438 FileDependenciesArray.AddRange (filenames);
442 public void AddFileDependency (string filename)
444 if (filename == null || filename == String.Empty)
446 FileDependenciesArray.Add (filename);
449 public void AddHeader (string name, string value)
451 AppendHeader (name, value);
454 public void AppendCookie (HttpCookie cookie)
456 Cookies.Add (cookie);
461 // Special case for Content-Length, Content-Type, Transfer-Encoding and Cache-Control
464 public void AppendHeader (string name, string value)
467 throw new HttpException ("headers have been already sent");
469 if (String.Compare (name, "content-length", true, CultureInfo.InvariantCulture) == 0){
470 content_length = (long) UInt64.Parse (value);
475 if (String.Compare (name, "content-type", true, CultureInfo.InvariantCulture) == 0){
480 if (String.Compare (name, "transfer-encoding", true, CultureInfo.InvariantCulture) == 0){
481 transfer_encoding = value;
486 if (String.Compare (name, "cache-control", true, CultureInfo.InvariantCulture) == 0){
487 user_cache_control = value;
491 headers.Add (new UnknownResponseHeader (name, value));
494 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
495 public void AppendToLog (string param)
497 Console.Write ("System.Web: ");
498 Console.WriteLine (param);
501 public string ApplyAppPathModifier (string virtualPath)
503 if (virtualPath == null)
506 if (virtualPath == "")
507 return context.Request.RootVirtualDir;
509 if (UrlUtils.IsRelativeUrl (virtualPath)) {
510 virtualPath = UrlUtils.Combine (context.Request.RootVirtualDir, virtualPath);
511 } else if (UrlUtils.IsRooted (virtualPath)) {
512 virtualPath = UrlUtils.Canonic (virtualPath);
515 if (app_path_mod != null && virtualPath.IndexOf (app_path_mod) < 0) {
516 string rvd = context.Request.RootVirtualDir;
517 string basevd = rvd.Replace (app_path_mod, "");
519 if (!StrUtils.StartsWith (virtualPath, basevd))
522 virtualPath = UrlUtils.Combine (rvd, virtualPath.Substring (basevd.Length));
528 public void BinaryWrite (byte [] buffer)
530 output_stream.Write (buffer, 0, buffer.Length);
533 internal void BinaryWrite (byte [] buffer, int start, int len)
535 output_stream.Write (buffer, start, len);
543 public void ClearContent ()
545 output_stream.Clear ();
549 public void ClearHeaders ()
552 throw new HttpException ("headers have been already sent");
554 // Reset the special case headers.
556 content_type = "text/html";
557 transfer_encoding = null;
558 user_cache_control = null;
562 internal bool HeadersSent {
572 if (WorkerRequest != null)
573 WorkerRequest.CloseConnection ();
582 if (context.TimeoutPossible) {
583 Thread.CurrentThread.Abort (FlagEnd);
585 // If this is called from an async event, signal the completion
587 HttpApplication app_instance = context.ApplicationInstance;
588 if (app_instance != null)
589 app_instance.CompleteRequest ();
596 // Transfer-Encoding (chunked)
598 void AddHeadersNoCache (ArrayList write_headers, bool final_flush)
604 write_headers.Add (new UnknownResponseHeader ("Transfer-Encoding", "chunked"));
605 else if (transfer_encoding != null)
606 write_headers.Add (new UnknownResponseHeader ("Transfer-Encoding", transfer_encoding));
608 UnknownResponseHeader date_header = new UnknownResponseHeader ("Date",
609 DateTime.UtcNow.ToString ("r", CultureInfo.InvariantCulture));
610 write_headers.Add (date_header);
613 cached_response.DateHeader = date_header;
615 if (redirect_location != null)
616 write_headers.Add (new UnknownResponseHeader ("Location", redirect_location));
619 // If Content-Length is set.
621 if (content_length >= 0) {
622 write_headers.Add (new KnownResponseHeader (HttpWorkerRequest.HeaderContentLength,
623 content_length.ToString (CultureInfo.InvariantCulture)));
624 } else if (BufferOutput) {
627 // If we are buffering and this is the last flush, not a middle-flush,
628 // we know the content-length.
631 content_length = output_stream.total;
632 write_headers.Add (new KnownResponseHeader (HttpWorkerRequest.HeaderContentLength,
633 content_length.ToString (CultureInfo.InvariantCulture)));
637 // We are buffering, and this is a flush in the middle.
638 // If we are not chunked, we need to set "Connection: close".
642 Console.WriteLine ("Setting to close2");
644 write_headers.Add (new KnownResponseHeader (HttpWorkerRequest.HeaderConnection, "close"));
649 // If the content-length is not set, and we are not buffering, we must
654 Console.WriteLine ("Setting to close");
656 write_headers.Add (new KnownResponseHeader (HttpWorkerRequest.HeaderConnection, "close"));
661 // Cache Control, the cache policy takes precedence over the cache_control property.
663 if (cache_policy != null)
664 cache_policy.SetHeaders (this, headers);
666 write_headers.Add (new UnknownResponseHeader ("Cache-Control", CacheControl));
671 if (content_type != null){
672 string header = content_type;
674 if (charset_set || header == "text/plain" || header == "text/html") {
675 if (header.IndexOf ("charset=") == -1) {
676 if (charset == null || charset == "")
677 charset = ContentEncoding.HeaderName;
678 header += "; charset=" + charset;
682 write_headers.Add (new UnknownResponseHeader ("Content-Type", header));
685 if (cookies != null && cookies.Count != 0){
686 int n = cookies.Count;
687 for (int i = 0; i < n; i++)
688 write_headers.Add (cookies.Get (i).GetCookieHeader ());
690 // For J2EE Portal support emulate cookies by storing them in the session.
691 context.Request.SetSessionCookiesForPortal (cookies);
696 internal void WriteHeaders (bool final_flush)
701 if (cached_response != null)
702 cached_response.SetHeaders (headers);
707 if (context != null) {
708 HttpApplication app_instance = context.ApplicationInstance;
709 if (app_instance != null)
710 app_instance.TriggerPreSendRequestHeaders ();
713 // If this page is cached use the cached headers
714 // instead of the standard headers
715 ArrayList write_headers = headers;
716 if (cached_headers != null)
717 write_headers = cached_headers;
719 AddHeadersNoCache (write_headers, final_flush);
721 if (WorkerRequest != null)
722 WorkerRequest.SendStatus (status_code, StatusDescription);
724 if (WorkerRequest != null) {
725 foreach (BaseResponseHeader header in write_headers){
726 header.SendContent (WorkerRequest);
732 internal void DoFilter (bool close)
734 if (output_stream.HaveFilter && context != null && context.Error == null)
735 output_stream.ApplyFilter (close);
738 internal void Flush (bool final_flush)
740 DoFilter (final_flush);
742 if (final_flush || status_code != 200)
746 bool head = ((context != null) && (context.Request.HttpMethod == "HEAD"));
747 if (suppress_content || head) {
750 output_stream.Clear ();
751 if (WorkerRequest != null)
752 output_stream.Flush (WorkerRequest, true); // ignore final_flush here.
757 WriteHeaders (final_flush);
759 if (context != null) {
760 HttpApplication app_instance = context.ApplicationInstance;
761 if (app_instance != null)
762 app_instance.TriggerPreSendRequestContent ();
766 MemoryStream ms = output_stream.GetData ();
767 cached_response.ContentLength = (int) ms.Length;
768 cached_response.SetData (ms.GetBuffer ());
771 if (WorkerRequest != null)
772 output_stream.Flush (WorkerRequest, final_flush);
780 public void Pics (string value)
782 AppendHeader ("PICS-Label", value);
785 public void Redirect (string url)
787 Redirect (url, true);
790 public void Redirect (string url, bool endResponse)
793 throw new HttpException ("Headers have already been sent");
796 is_request_being_redirected = true;
802 url = ApplyAppPathModifier (url);
803 redirect_location = url;
805 // Text for browsers that can't handle location header
806 Write ("<html><head><title>Object moved</title></head><body>\r\n");
807 Write ("<h2>Object moved to <a href='" + url + "'>here</a></h2>\r\n");
808 Write ("</body><html>\r\n");
813 is_request_being_redirected = false;
817 public static void RemoveOutputCacheItem (string path)
820 throw new ArgumentNullException ("path");
822 if (path.Length == 0)
826 throw new ArgumentException ("'" + path + "' is not an absolute virtual path.");
828 HttpRuntime.InternalCache.Remove (path);
831 public void SetCookie (HttpCookie cookie)
833 AppendCookie (cookie);
836 public void Write (char ch)
841 public void Write (object obj)
846 Output.Write (obj.ToString ());
849 public void Write (string s)
854 public void Write (char [] buffer, int index, int count)
856 Output.Write (buffer, index, count);
859 internal void WriteFile (FileStream fs, long offset, long size)
861 byte [] buffer = new byte [32*1024];
864 fs.Position = offset;
868 while (remain > 0 && (n = fs.Read (buffer, 0, (int) Math.Min (remain, 32*1024))) != 0){
870 output_stream.Write (buffer, 0, n);
874 public void WriteFile (string filename)
876 WriteFile (filename, false);
879 public void WriteFile (string filename, bool readIntoMemory)
881 if (filename == null)
882 throw new ArgumentNullException ("filename");
885 using (FileStream fs = File.OpenRead (filename))
886 WriteFile (fs, 0, fs.Length);
888 FileInfo fi = new FileInfo (filename);
889 output_stream.WriteFile (filename, 0, fi.Length);
894 output_stream.ApplyFilter (false);
899 public void WriteFile (IntPtr fileHandle, long offset, long size) {
900 throw new PlatformNotSupportedException("IntPtr not supported");
903 public void WriteFile (IntPtr fileHandle, long offset, long size)
906 throw new ArgumentNullException ("offset can not be negative");
908 throw new ArgumentNullException ("size can not be negative");
913 // Note: this .ctor will throw a SecurityException if the caller
914 // doesn't have the UnmanagedCode permission
915 using (FileStream fs = new FileStream (fileHandle, FileAccess.Read))
916 WriteFile (fs, offset, size);
920 output_stream.ApplyFilter (false);
925 public void WriteFile (string filename, long offset, long size)
927 if (filename == null)
928 throw new ArgumentNullException ("filename");
930 throw new ArgumentNullException ("offset can not be negative");
932 throw new ArgumentNullException ("size can not be negative");
937 FileStream fs = File.OpenRead (filename);
938 WriteFile (fs, offset, size);
943 output_stream.ApplyFilter (false);
947 [MonoTODO ("Not implemented")]
948 public void WriteSubstitution (HttpResponseSubstitutionCallback callback)
950 throw new NotImplementedException ();
954 // Like WriteFile, but never buffers, so we manually Flush here
956 public void TransmitFile (string filename)
958 if (filename == null)
959 throw new ArgumentNullException ("filename");
961 TransmitFile (filename, false);
964 internal void TransmitFile (string filename, bool final_flush)
966 FileInfo fi = new FileInfo (filename);
967 using (Stream s = fi.OpenRead ()); // Just check if we can read.
968 output_stream.WriteFile (filename, 0, fi.Length);
969 output_stream.ApplyFilter (final_flush);
974 #region Session state support
975 internal void SetAppPathModifier (string app_modifier)
977 app_path_mod = app_modifier;
981 #region Cache Support
982 internal void SetCachedHeaders (ArrayList headers)
984 cached_headers = headers;
987 internal bool IsCached {
989 return cached_response != null;
993 public HttpCachePolicy Cache {
995 if (cache_policy == null) {
996 cache_policy = new HttpCachePolicy ();
997 cache_policy.CacheabilityUpdated += new CacheabilityUpdatedCallback (OnCacheabilityUpdated);
1000 return cache_policy;
1004 private void OnCacheabilityUpdated (object sender, CacheabilityUpdatedEventArgs e)
1006 if (e.Cacheability >= HttpCacheability.Server && !IsCached)
1007 cached_response = new CachedRawResponse (cache_policy);
1008 else if (e.Cacheability <= HttpCacheability.Private)
1009 cached_response = null;
1012 internal CachedRawResponse GetCachedResponse ()
1014 cached_response.StatusCode = StatusCode;
1015 cached_response.StatusDescription = StatusDescription;
1016 return cached_response;
1020 // This is one of the old ASP compatibility methods, the real cache
1021 // control is in the Cache property, and this is a second class citizen
1023 public string CacheControl {
1025 if (value == null || value == "") {
1026 Cache.SetCacheability (HttpCacheability.NoCache);
1027 user_cache_control = null;
1028 } else if (String.Compare (value, "public", true, CultureInfo.InvariantCulture) == 0) {
1029 Cache.SetCacheability (HttpCacheability.Public);
1030 user_cache_control = "public";
1031 } else if (String.Compare (value, "private", true, CultureInfo.InvariantCulture) == 0) {
1032 Cache.SetCacheability (HttpCacheability.Private);
1033 user_cache_control = "private";
1034 } else if (String.Compare (value, "no-cache", true, CultureInfo.InvariantCulture) == 0) {
1035 Cache.SetCacheability (HttpCacheability.NoCache);
1036 user_cache_control = "no-cache";
1038 throw new ArgumentException ("CacheControl property only allows `public', " +
1039 "`private' or no-cache, for different uses, use " +
1040 "Response.AppendHeader");
1043 get { return (user_cache_control != null) ? user_cache_control : "private"; }
1047 internal int GetOutputByteCount ()
1049 return output_stream.GetTotalLength ();
1052 internal void ReleaseResources ()
1054 output_stream.ReleaseResources (true);
1055 output_stream = null;