2 // System.Web.HttpResponse.cs
6 // Miguel de Icaza (miguel@novell.com)
7 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // Marek Habersack <mhabersack@novell.com>
10 // Copyright (C) 2005-2010 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.
34 using System.Collections;
35 using System.Collections.Specialized;
37 using System.Web.Caching;
38 using System.Threading;
39 using System.Web.Util;
40 using System.Web.Configuration;
41 using System.Globalization;
42 using System.Security.Permissions;
43 using System.Web.Hosting;
44 using System.Web.SessionState;
46 using System.Web.Routing;
50 // CAS - no InheritanceDemand here as the class is sealed
51 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
52 public sealed partial class HttpResponse
54 internal HttpWorkerRequest WorkerRequest;
55 internal HttpResponseStream output_stream;
56 internal bool buffer = true;
58 ArrayList fileDependencies;
62 HttpCachePolicy cache_policy;
64 HttpCookieCollection cookies;
66 int status_code = 200;
67 string status_description = "OK";
69 string content_type = "text/html";
72 CachedRawResponse cached_response;
73 string user_cache_control = "private";
74 string redirect_location;
75 string version_header;
76 bool version_header_checked;
79 // Negative Content-Length means we auto-compute the size of content-length
80 // can be overwritten with AppendHeader ("Content-Length", value)
82 long content_length = -1;
85 // The list of the headers that we will send back to the client, except
86 // the headers that we compute here.
89 HttpHeaderCollection headers;
91 NameValueCollection cached_headers;
94 // Transfer encoding state
96 string transfer_encoding;
97 internal bool use_chunked;
101 internal bool suppress_content;
107 bool is_request_being_redirected;
108 Encoding headerEncoding;
110 internal HttpResponse ()
112 output_stream = new HttpResponseStream (this);
113 writer = new HttpWriter (this);
116 public HttpResponse (TextWriter writer) : this ()
119 this.writer = writer;
122 internal HttpResponse (HttpWorkerRequest worker_request, HttpContext context) : this ()
124 WorkerRequest = worker_request;
125 this.context = context;
127 if (worker_request != null && worker_request.GetHttpVersion () == "HTTP/1.1") {
128 string gi = worker_request.GetServerVariable ("GATEWAY_INTERFACE");
129 use_chunked = (String.IsNullOrEmpty (gi) ||
130 !gi.StartsWith ("cgi", StringComparison.OrdinalIgnoreCase));
134 writer = new HttpWriter (this);
137 internal TextWriter SetTextWriter (TextWriter writer)
139 TextWriter prev = this.writer;
140 this.writer = writer;
144 internal string VersionHeader {
146 if (!version_header_checked && version_header == null) {
147 version_header_checked = true;
148 HttpRuntimeSection config = HttpRuntime.Section;
149 if (config != null && config.EnableVersionHeader)
150 version_header = Environment.Version.ToString (3);
153 return version_header;
157 internal HttpContext Context {
158 get { return context; }
159 set { context = value; }
162 internal string[] FileDependencies {
164 if (fileDependencies == null || fileDependencies.Count == 0)
165 return new string[0] {};
166 return (string[]) fileDependencies.ToArray (typeof (string));
170 ArrayList FileDependenciesArray {
172 if (fileDependencies == null)
173 fileDependencies = new ArrayList ();
174 return fileDependencies;
188 public bool BufferOutput {
199 // Use the default from <globalization> section if the client has not set the encoding
201 public Encoding ContentEncoding {
203 if (encoding == null) {
204 if (context != null) {
205 string client_content_type = context.Request.ContentType;
206 string parameter = HttpRequest.GetParameter (client_content_type, "; charset=");
207 if (parameter != null) {
209 // Do what the #1 web server does
210 encoding = Encoding.GetEncoding (parameter);
215 if (encoding == null)
216 encoding = WebEncoding.ResponseEncoding;
223 throw new ArgumentException ("ContentEncoding can not be null");
226 HttpWriter http_writer = writer as HttpWriter;
227 if (http_writer != null)
228 http_writer.SetEncoding (encoding);
232 public string ContentType {
238 content_type = value;
242 public string Charset {
245 charset = ContentEncoding.WebName;
256 public HttpCookieCollection Cookies {
259 cookies = new HttpCookieCollection (true, false);
266 if (cache_policy == null)
269 return cache_policy.ExpireMinutes ();
273 Cache.SetExpires (DateTime.Now + new TimeSpan (0, value, 0));
277 public DateTime ExpiresAbsolute {
279 return Cache.Expires;
283 Cache.SetExpires (value);
287 public Stream Filter {
289 if (WorkerRequest == null)
292 return output_stream.Filter;
296 output_stream.Filter = value;
300 public Encoding HeaderEncoding {
302 if (headerEncoding == null) {
303 GlobalizationSection gs = WebConfigurationManager.SafeGetSection ("system.web/globalization", typeof (GlobalizationSection)) as GlobalizationSection;
306 headerEncoding = Encoding.UTF8;
308 headerEncoding = gs.ResponseHeaderEncoding;
309 if (headerEncoding == Encoding.Unicode)
310 throw new HttpException ("HeaderEncoding must not be Unicode");
313 return headerEncoding;
317 throw new HttpException ("headers have already been sent");
319 throw new ArgumentNullException ("HeaderEncoding");
320 if (value == Encoding.Unicode)
321 throw new HttpException ("HeaderEncoding must not be Unicode");
322 headerEncoding = value;
326 public NameValueCollection Headers {
329 headers = new HttpHeaderCollection ();
336 public bool IsClientConnected {
338 if (WorkerRequest == null)
339 return true; // yep that's true
341 return WorkerRequest.IsClientConnected ();
345 public bool IsRequestBeingRedirected {
346 get { return is_request_being_redirected; }
349 public TextWriter Output {
353 set { writer = value; }
356 public Stream OutputStream {
358 return output_stream;
362 public string RedirectLocation {
364 return redirect_location;
368 redirect_location = value;
372 public string Status {
373 get { return String.Concat (status_code.ToString (), " ", StatusDescription); }
376 int p = value.IndexOf (' ');
378 throw new HttpException ("Invalid format for the Status property");
380 string s = value.Substring (0, p);
382 if (!Int32.TryParse (s, out status_code))
383 throw new HttpException ("Invalid format for the Status property");
385 status_description = value.Substring (p+1);
389 // We ignore the two properties on Mono as they are for use with IIS7, but there is
390 // no point in throwing PlatformNotSupportedException. We might find a use for them
392 public int SubStatusCode {
398 public bool SuppressFormsAuthenticationRedirect {
404 public bool TrySkipIisCustomErrors {
409 public int StatusCode {
416 throw new HttpException ("headers have already been sent");
419 status_description = null;
423 public string StatusDescription {
425 if (status_description == null)
426 status_description = HttpWorkerRequest.GetStatusDescription (status_code);
428 return status_description;
433 throw new HttpException ("headers have already been sent");
435 status_description = value;
439 public bool SuppressContent {
441 return suppress_content;
445 suppress_content = value;
449 [MonoTODO ("Not implemented")]
450 public void AddCacheDependency (params CacheDependency[] dependencies)
452 throw new NotImplementedException ();
455 [MonoTODO ("Not implemented")]
456 public void AddCacheItemDependencies (string[] cacheKeys)
458 throw new NotImplementedException ();
461 [MonoTODO("Currently does nothing")]
462 public void AddCacheItemDependencies (ArrayList cacheKeys)
464 // TODO: talk to jackson about the cache
467 [MonoTODO("Currently does nothing")]
468 public void AddCacheItemDependency (string cacheKey)
470 // TODO: talk to jackson about the cache
473 public void AddFileDependencies (ArrayList filenames)
475 if (filenames == null || filenames.Count == 0)
477 FileDependenciesArray.AddRange (filenames);
480 public void AddFileDependencies (string[] filenames)
482 if (filenames == null || filenames.Length == 0)
484 FileDependenciesArray.AddRange (filenames);
487 public void AddFileDependency (string filename)
489 if (filename == null || filename == String.Empty)
491 FileDependenciesArray.Add (filename);
494 public void AddHeader (string name, string value)
496 AppendHeader (name, value);
499 public void AppendCookie (HttpCookie cookie)
501 Cookies.Add (cookie);
506 // Special case for Content-Length, Content-Type, Transfer-Encoding and Cache-Control
509 public void AppendHeader (string name, string value)
512 throw new HttpException ("Headers have been already sent");
513 if (String.Compare (name, "content-length", StringComparison.OrdinalIgnoreCase) == 0){
514 content_length = (long) UInt64.Parse (value);
519 if (String.Compare (name, "content-type", StringComparison.OrdinalIgnoreCase) == 0){
524 if (String.Compare (name, "transfer-encoding", StringComparison.OrdinalIgnoreCase) == 0){
525 transfer_encoding = value;
530 if (String.Compare (name, "cache-control", StringComparison.OrdinalIgnoreCase) == 0){
531 user_cache_control = value;
535 Headers.Add (name, value);
538 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
539 public void AppendToLog (string param)
541 Console.Write ("System.Web: ");
542 Console.WriteLine (param);
545 public string ApplyAppPathModifier (string virtualPath)
547 if (virtualPath == null || context == null)
550 if (virtualPath.Length == 0)
551 return context.Request.RootVirtualDir;
553 if (UrlUtils.IsRelativeUrl (virtualPath)) {
554 virtualPath = UrlUtils.Combine (context.Request.RootVirtualDir, virtualPath);
555 } else if (UrlUtils.IsRooted (virtualPath)) {
556 virtualPath = UrlUtils.Canonic (virtualPath);
559 bool cookieless = false;
560 SessionStateSection config = WebConfigurationManager.GetWebApplicationSection ("system.web/sessionState") as SessionStateSection;
561 cookieless = SessionStateModule.IsCookieLess (context, config);
566 if (app_path_mod != null && virtualPath.IndexOf (app_path_mod) < 0) {
567 if (UrlUtils.HasSessionId (virtualPath))
568 virtualPath = UrlUtils.RemoveSessionId (VirtualPathUtility.GetDirectory (virtualPath), virtualPath);
569 return UrlUtils.InsertSessionId (app_path_mod, virtualPath);
575 public void BinaryWrite (byte [] buffer)
577 output_stream.Write (buffer, 0, buffer.Length);
580 internal void BinaryWrite (byte [] buffer, int start, int len)
582 output_stream.Write (buffer, start, len);
590 public void ClearContent ()
592 output_stream.Clear ();
596 public void ClearHeaders ()
599 throw new HttpException ("headers have been already sent");
601 // Reset the special case headers.
603 content_type = "text/html";
604 transfer_encoding = null;
605 user_cache_control = "private";
606 if (cache_policy != null)
607 cache_policy.Cacheability = HttpCacheability.Private;
613 internal bool HeadersSent {
623 if (WorkerRequest != null)
624 WorkerRequest.CloseConnection ();
628 public void DisableKernelCache ()
630 // does nothing in Mono
638 if (context.TimeoutPossible) {
639 Thread.CurrentThread.Abort (FlagEnd.Value);
641 // If this is called from an async event, signal the completion
643 HttpApplication app_instance = context.ApplicationInstance;
644 if (app_instance != null)
645 app_instance.CompleteRequest ();
652 // Transfer-Encoding (chunked)
655 void AddHeadersNoCache (NameValueCollection write_headers, bool final_flush)
661 write_headers.Add ("Transfer-Encoding", "chunked");
662 else if (transfer_encoding != null)
663 write_headers.Add ("Transfer-Encoding", transfer_encoding);
664 if (redirect_location != null)
665 write_headers.Add ("Location", redirect_location);
667 string vh = VersionHeader;
669 write_headers.Add ("X-AspNet-Version", vh);
672 // If Content-Length is set.
674 if (content_length >= 0) {
675 write_headers.Add (HttpWorkerRequest.GetKnownResponseHeaderName (HttpWorkerRequest.HeaderContentLength),
676 content_length.ToString (Helpers.InvariantCulture));
677 } else if (BufferOutput) {
680 // If we are buffering and this is the last flush, not a middle-flush,
681 // we know the content-length.
683 content_length = output_stream.total;
684 write_headers.Add (HttpWorkerRequest.GetKnownResponseHeaderName (HttpWorkerRequest.HeaderContentLength),
685 content_length.ToString (Helpers.InvariantCulture));
688 // We are buffering, and this is a flush in the middle.
689 // If we are not chunked, we need to set "Connection: close".
692 write_headers.Add (HttpWorkerRequest.GetKnownResponseHeaderName (HttpWorkerRequest.HeaderConnection), "close");
697 // If the content-length is not set, and we are not buffering, we must
701 write_headers.Add (HttpWorkerRequest.GetKnownResponseHeaderName (HttpWorkerRequest.HeaderConnection), "close");
706 // Cache Control, the cache policy takes precedence over the cache_control property.
708 if (cache_policy != null)
709 cache_policy.SetHeaders (this, headers);
711 write_headers.Add ("Cache-Control", CacheControl);
716 if (content_type != null){
717 string header = content_type;
719 if (charset_set || header == "text/plain" || header == "text/html") {
720 if (header.IndexOf ("charset=") == -1 && !string.IsNullOrEmpty (charset)) {
721 header += "; charset=" + charset;
725 write_headers.Add ("Content-Type", header);
728 if (cookies != null && cookies.Count != 0){
729 int n = cookies.Count;
730 for (int i = 0; i < n; i++)
731 write_headers.Add ("Set-Cookie", cookies.Get (i).GetCookieHeaderValue ());
735 internal void WriteHeaders (bool final_flush)
743 if (context != null) {
744 HttpApplication app_instance = context.ApplicationInstance;
745 if (app_instance != null)
746 app_instance.TriggerPreSendRequestHeaders ();
751 if (cached_response != null)
752 cached_response.SetHeaders (headers);
754 // If this page is cached use the cached headers
755 // instead of the standard headers
756 NameValueCollection write_headers;
757 if (cached_headers != null)
758 write_headers = cached_headers;
760 write_headers = Headers;
761 AddHeadersNoCache (write_headers, final_flush);
764 if (WorkerRequest != null)
765 WorkerRequest.SendStatus (status_code, StatusDescription);
767 if (WorkerRequest != null) {
772 for (int i = 0; i < write_headers.Count; i++) {
773 header_name = write_headers.GetKey (i);
774 header_index = HttpWorkerRequest.GetKnownResponseHeaderIndex (header_name);
775 values = write_headers.GetValues (i);
779 foreach (string val in values) {
780 if (header_index > -1)
781 WorkerRequest.SendKnownResponseHeader (header_index, val);
783 WorkerRequest.SendUnknownResponseHeader (header_name, val);
789 internal void DoFilter (bool close)
791 if (output_stream.HaveFilter && context != null && context.Error == null)
792 output_stream.ApplyFilter (close);
795 internal void Flush (bool final_flush)
798 throw new HttpException ("Server cannot flush a completed response");
800 DoFilter (final_flush);
802 if (final_flush || status_code != 200)
806 bool head = ((context != null) && (context.Request.HttpMethod == "HEAD"));
807 if (suppress_content || head) {
810 output_stream.Clear ();
811 if (WorkerRequest != null)
812 output_stream.Flush (WorkerRequest, true); // ignore final_flush here.
816 completed = final_flush;
819 WriteHeaders (final_flush);
821 if (context != null) {
822 HttpApplication app_instance = context.ApplicationInstance;
823 if (app_instance != null)
824 app_instance.TriggerPreSendRequestContent ();
828 cached_response.SetData (output_stream.GetData ());
830 if (WorkerRequest != null)
831 output_stream.Flush (WorkerRequest, final_flush);
839 public void Pics (string value)
841 AppendHeader ("PICS-Label", value);
844 void Redirect (string url, bool endResponse, int code)
847 throw new ArgumentNullException ("url");
850 throw new HttpException ("Headers have already been sent");
852 if (url.IndexOf ('\n') != -1)
853 throw new ArgumentException ("Redirect URI cannot contain newline characters.", "url");
855 is_request_being_redirected = true;
860 url = ApplyAppPathModifier (url);
862 bool isFullyQualified;
863 if (StrUtils.StartsWith (url, "http:", true) ||
864 StrUtils.StartsWith (url, "https:", true) ||
865 StrUtils.StartsWith (url, "file:", true) ||
866 StrUtils.StartsWith (url, "ftp:", true))
867 isFullyQualified = true;
869 isFullyQualified = false;
871 if (!isFullyQualified) {
872 HttpRuntimeSection config = HttpRuntime.Section;
873 if (config != null && config.UseFullyQualifiedRedirectUrl) {
874 var ub = new UriBuilder (context.Request.Url);
875 int qpos = url.IndexOf ('?');
880 ub.Path = url.Substring (0, qpos);
881 ub.Query = url.Substring (qpos + 1);
886 url = ub.Uri.ToString ();
890 redirect_location = url;
892 // Text for browsers that can't handle location header
893 Write ("<html><head><title>Object moved</title></head><body>\r\n");
894 Write ("<h2>Object moved to <a href=\"" + url + "\">here</a></h2>\r\n");
895 Write ("</body><html>\r\n");
899 is_request_being_redirected = false;
902 public void Redirect (string url)
904 Redirect (url, true);
907 public void Redirect (string url, bool endResponse)
909 Redirect (url, endResponse, 302);
911 public void RedirectPermanent (string url)
913 RedirectPermanent (url, true);
916 public void RedirectPermanent (string url, bool endResponse)
918 Redirect (url, endResponse, 301);
921 public void RedirectToRoute (object routeValues)
923 RedirectToRoute ("RedirectToRoute", null, new RouteValueDictionary (routeValues), 302, true);
926 public void RedirectToRoute (RouteValueDictionary routeValues)
928 RedirectToRoute ("RedirectToRoute", null, routeValues, 302, true);
931 public void RedirectToRoute (string routeName)
933 RedirectToRoute ("RedirectToRoute", routeName, null, 302, true);
936 public void RedirectToRoute (string routeName, object routeValues)
938 RedirectToRoute ("RedirectToRoute", routeName, new RouteValueDictionary (routeValues), 302, true);
941 public void RedirectToRoute (string routeName, RouteValueDictionary routeValues)
943 RedirectToRoute ("RedirectToRoute", routeName, routeValues, 302, true);
946 public void RedirectToRoutePermanent (object routeValues)
948 RedirectToRoute ("RedirectToRoutePermanent", null, new RouteValueDictionary (routeValues), 301, false);
951 public void RedirectToRoutePermanent (RouteValueDictionary routeValues)
953 RedirectToRoute ("RedirectToRoutePermanent", null, routeValues, 301, false);
956 public void RedirectToRoutePermanent (string routeName)
958 RedirectToRoute ("RedirectToRoutePermanent", routeName, null, 301, false);
961 public void RedirectToRoutePermanent (string routeName, object routeValues)
963 RedirectToRoute ("RedirectToRoutePermanent", routeName, new RouteValueDictionary (routeValues), 301, false);
966 public void RedirectToRoutePermanent (string routeName, RouteValueDictionary routeValues)
968 RedirectToRoute ("RedirectToRoutePermanent", routeName, routeValues, 301, false);
971 void RedirectToRoute (string callerName, string routeName, RouteValueDictionary routeValues, int redirectCode, bool endResponse)
973 HttpContext ctx = context ?? HttpContext.Current;
974 HttpRequest req = ctx != null ? ctx.Request : null;
977 // Let's emulate .NET
978 throw new NullReferenceException ();
980 VirtualPathData vpd = RouteTable.Routes.GetVirtualPath (req.RequestContext, routeName, routeValues);
981 string redirectUrl = vpd != null ? vpd.VirtualPath : null;
982 if (String.IsNullOrEmpty (redirectUrl))
983 throw new InvalidOperationException ("No matching route found for RedirectToRoute");
985 Redirect (redirectUrl, true, redirectCode);
988 public static void RemoveOutputCacheItem (string path, string providerName)
991 throw new ArgumentNullException ("path");
993 if (path.Length > 0 && path [0] != '/')
994 throw new ArgumentException ("Invalid path for HttpResponse.RemoveOutputCacheItem: '" + path + "'. An absolute virtual path is expected");
996 OutputCache.RemoveFromProvider (path, providerName);
998 public static void RemoveOutputCacheItem (string path)
1001 throw new ArgumentNullException ("path");
1003 if (path.Length == 0)
1006 if (path [0] != '/')
1007 throw new ArgumentException ("'" + path + "' is not an absolute virtual path.");
1009 RemoveOutputCacheItem (path, OutputCache.DefaultProviderName);
1012 public void SetCookie (HttpCookie cookie)
1014 AppendCookie (cookie);
1017 public void Write (char ch)
1019 TextWriter writer = Output;
1022 throw new NullReferenceException (".NET 4.0 emulation. A null value was found where an object was required.");
1026 public void Write (object obj)
1028 TextWriter writer = Output;
1031 throw new NullReferenceException (".NET 4.0 emulation. A null value was found where an object was required.");
1035 writer.Write (obj.ToString ());
1038 public void Write (string s)
1040 TextWriter writer = Output;
1043 throw new NullReferenceException (".NET 4.0 emulation. A null value was found where an object was required.");
1047 public void Write (char [] buffer, int index, int count)
1049 TextWriter writer = Output;
1052 throw new NullReferenceException (".NET 4.0 emulation. A null value was found where an object was required.");
1053 writer.Write (buffer, index, count);
1056 bool IsFileSystemDirSeparator (char ch)
1058 return ch == '\\' || ch == '/';
1061 string GetNormalizedFileName (string fn)
1063 if (String.IsNullOrEmpty (fn))
1066 // On Linux we don't change \ to / since filenames with \ are valid. We also
1067 // don't remove drive: designator for the same reason.
1068 int len = fn.Length;
1069 if (len >= 3 && fn [1] == ':' && IsFileSystemDirSeparator (fn [2]))
1070 return Path.GetFullPath (fn); // drive-qualified absolute file path
1072 bool startsWithDirSeparator = IsFileSystemDirSeparator (fn [0]);
1073 if (len >= 2 && startsWithDirSeparator && IsFileSystemDirSeparator (fn [1]))
1074 return Path.GetFullPath (fn); // UNC path
1076 if (!startsWithDirSeparator) {
1077 HttpContext ctx = context ?? HttpContext.Current;
1078 HttpRequest req = ctx != null ? ctx.Request : null;
1081 return req.MapPath (fn);
1084 return fn; // Or should we rather throw?
1087 internal void WriteFile (FileStream fs, long offset, long size)
1089 byte [] buffer = new byte [32*1024];
1092 fs.Position = offset;
1096 while (remain > 0 && (n = fs.Read (buffer, 0, (int) Math.Min (remain, 32*1024))) != 0){
1098 output_stream.Write (buffer, 0, n);
1102 public void WriteFile (string filename)
1104 WriteFile (filename, false);
1107 public void WriteFile (string filename, bool readIntoMemory)
1109 if (filename == null)
1110 throw new ArgumentNullException ("filename");
1112 string fn = GetNormalizedFileName (filename);
1113 if (readIntoMemory){
1114 using (FileStream fs = File.OpenRead (fn))
1115 WriteFile (fs, 0, fs.Length);
1117 FileInfo fi = new FileInfo (fn);
1118 output_stream.WriteFile (fn, 0, fi.Length);
1123 output_stream.ApplyFilter (false);
1127 public void WriteFile (IntPtr fileHandle, long offset, long size)
1130 throw new ArgumentNullException ("offset can not be negative");
1132 throw new ArgumentNullException ("size can not be negative");
1137 // Note: this .ctor will throw a SecurityException if the caller
1138 // doesn't have the UnmanagedCode permission
1139 using (FileStream fs = new FileStream (fileHandle, FileAccess.Read))
1140 WriteFile (fs, offset, size);
1144 output_stream.ApplyFilter (false);
1148 public void WriteFile (string filename, long offset, long size)
1150 if (filename == null)
1151 throw new ArgumentNullException ("filename");
1153 throw new ArgumentNullException ("offset can not be negative");
1155 throw new ArgumentNullException ("size can not be negative");
1160 FileStream fs = File.OpenRead (filename);
1161 WriteFile (fs, offset, size);
1166 output_stream.ApplyFilter (false);
1170 public void WriteSubstitution (HttpResponseSubstitutionCallback callback)
1172 // Emulation of .NET behavior
1173 if (callback == null)
1174 throw new NullReferenceException ();
1176 object target = callback.Target;
1177 if (target != null && target.GetType () == typeof (Control))
1178 throw new ArgumentException ("callback");
1180 string s = callback (context);
1186 Cache.Cacheability = HttpCacheability.Server;
1188 if (WorkerRequest == null)
1189 Write (s); // better this than nothing
1191 byte[] bytes = WebEncoding.ResponseEncoding.GetBytes (s);
1192 WorkerRequest.SendResponseFromMemory (bytes, bytes.Length);
1195 cached_response.SetData (callback);
1199 // Like WriteFile, but never buffers, so we manually Flush here
1201 public void TransmitFile (string filename)
1203 if (filename == null)
1204 throw new ArgumentNullException ("filename");
1206 TransmitFile (filename, false);
1209 internal void TransmitFile (string filename, bool final_flush)
1211 FileInfo fi = new FileInfo (filename);
1212 using (Stream s = fi.OpenRead ()); // Just check if we can read.
1213 output_stream.WriteFile (filename, 0, fi.Length);
1214 output_stream.ApplyFilter (final_flush);
1215 Flush (final_flush);
1218 public void TransmitFile (string filename, long offset, long length)
1220 output_stream.WriteFile (filename, offset, length);
1221 output_stream.ApplyFilter (false);
1225 internal void TransmitFile (VirtualFile vf)
1227 TransmitFile (vf, false);
1230 const int bufLen = 65535;
1231 internal void TransmitFile (VirtualFile vf, bool final_flush)
1234 throw new ArgumentNullException ("vf");
1236 if (vf is DefaultVirtualFile) {
1237 TransmitFile (HostingEnvironment.MapPath (vf.VirtualPath), final_flush);
1241 byte[] buf = new byte [bufLen];
1242 using (Stream s = vf.Open ()) {
1244 while ((readBytes = s.Read (buf, 0, bufLen)) > 0) {
1245 output_stream.Write (buf, 0, readBytes);
1246 output_stream.ApplyFilter (final_flush);
1254 #region Session state support
1255 internal void SetAppPathModifier (string app_modifier)
1257 app_path_mod = app_modifier;
1261 #region Cache Support
1262 internal void SetCachedHeaders (NameValueCollection headers)
1264 cached_headers = headers;
1268 internal bool IsCached {
1269 get { return cached_response != null; }
1272 cached_response = new CachedRawResponse (cache_policy);
1274 cached_response = null;
1278 public HttpCachePolicy Cache {
1280 if (cache_policy == null)
1281 cache_policy = new HttpCachePolicy ();
1283 return cache_policy;
1287 internal CachedRawResponse GetCachedResponse ()
1289 if (cached_response != null) {
1290 cached_response.StatusCode = StatusCode;
1291 cached_response.StatusDescription = StatusDescription;
1294 return cached_response;
1298 // This is one of the old ASP compatibility methods, the real cache
1299 // control is in the Cache property, and this is a second class citizen
1301 public string CacheControl {
1303 if (value == null || value == "") {
1304 Cache.SetCacheability (HttpCacheability.NoCache);
1305 user_cache_control = null;
1306 } else if (String.Compare (value, "public", true, Helpers.InvariantCulture) == 0) {
1307 Cache.SetCacheability (HttpCacheability.Public);
1308 user_cache_control = "public";
1309 } else if (String.Compare (value, "private", true, Helpers.InvariantCulture) == 0) {
1310 Cache.SetCacheability (HttpCacheability.Private);
1311 user_cache_control = "private";
1312 } else if (String.Compare (value, "no-cache", true, Helpers.InvariantCulture) == 0) {
1313 Cache.SetCacheability (HttpCacheability.NoCache);
1314 user_cache_control = "no-cache";
1316 throw new ArgumentException ("CacheControl property only allows `public', " +
1317 "`private' or no-cache, for different uses, use " +
1318 "Response.AppendHeader");
1321 get { return (user_cache_control != null) ? user_cache_control : "private"; }
1325 internal int GetOutputByteCount ()
1327 return output_stream.GetTotalLength ();
1330 internal void ReleaseResources ()
1332 if (output_stream != null)
1333 output_stream.ReleaseResources (true);
1342 static class FlagEnd
1344 public static readonly object Value = new object ();