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;
47 using System.Web.Routing;
52 // CAS - no InheritanceDemand here as the class is sealed
53 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
54 public sealed partial class HttpResponse
56 internal HttpWorkerRequest WorkerRequest;
57 internal HttpResponseStream output_stream;
58 internal bool buffer = true;
60 ArrayList fileDependencies;
64 HttpCachePolicy cache_policy;
66 HttpCookieCollection cookies;
68 int status_code = 200;
69 string status_description = "OK";
71 string content_type = "text/html";
74 CachedRawResponse cached_response;
75 string user_cache_control = "private";
76 string redirect_location;
77 string version_header;
78 bool version_header_checked;
81 // Negative Content-Length means we auto-compute the size of content-length
82 // can be overwritten with AppendHeader ("Content-Length", value)
84 long content_length = -1;
87 // The list of the headers that we will send back to the client, except
88 // the headers that we compute here.
91 HttpHeaderCollection headers;
93 NameValueCollection cached_headers;
96 // Transfer encoding state
98 string transfer_encoding;
99 internal bool use_chunked;
103 internal bool suppress_content;
109 bool is_request_being_redirected;
110 Encoding headerEncoding;
112 internal HttpResponse ()
114 output_stream = new HttpResponseStream (this);
115 writer = new HttpWriter (this);
118 public HttpResponse (TextWriter writer) : this ()
121 this.writer = writer;
124 internal HttpResponse (HttpWorkerRequest worker_request, HttpContext context) : this ()
126 WorkerRequest = worker_request;
127 this.context = context;
130 if (worker_request != null)
131 use_chunked = (worker_request.GetHttpVersion () == "HTTP/1.1");
133 writer = new HttpWriter (this);
136 internal TextWriter SetTextWriter (TextWriter writer)
138 TextWriter prev = this.writer;
139 this.writer = writer;
143 internal string VersionHeader {
145 if (!version_header_checked && version_header == null) {
146 version_header_checked = true;
147 HttpRuntimeSection config = HttpRuntime.Section;
148 if (config != null && config.EnableVersionHeader)
149 version_header = Environment.Version.ToString (3);
152 return version_header;
156 internal HttpContext Context {
157 get { return context; }
158 set { context = value; }
161 internal string[] FileDependencies {
163 if (fileDependencies == null || fileDependencies.Count == 0)
164 return new string[0] {};
165 return (string[]) fileDependencies.ToArray (typeof (string));
169 ArrayList FileDependenciesArray {
171 if (fileDependencies == null)
172 fileDependencies = new ArrayList ();
173 return fileDependencies;
187 public bool BufferOutput {
198 // Use the default from <globalization> section if the client has not set the encoding
200 public Encoding ContentEncoding {
202 if (encoding == null) {
203 if (context != null) {
204 string client_content_type = context.Request.ContentType;
205 string parameter = HttpRequest.GetParameter (client_content_type, "; charset=");
206 if (parameter != null) {
208 // Do what the #1 web server does
209 encoding = Encoding.GetEncoding (parameter);
214 if (encoding == null)
215 encoding = WebEncoding.ResponseEncoding;
222 throw new ArgumentException ("ContentEncoding can not be null");
225 HttpWriter http_writer = writer as HttpWriter;
226 if (http_writer != null)
227 http_writer.SetEncoding (encoding);
231 public string ContentType {
237 content_type = value;
241 public string Charset {
244 charset = ContentEncoding.WebName;
255 public HttpCookieCollection Cookies {
258 cookies = new HttpCookieCollection (true, false);
265 if (cache_policy == null)
268 return cache_policy.ExpireMinutes ();
272 Cache.SetExpires (DateTime.Now + new TimeSpan (0, value, 0));
276 public DateTime ExpiresAbsolute {
278 return Cache.Expires;
282 Cache.SetExpires (value);
286 public Stream Filter {
288 if (WorkerRequest == null)
291 return output_stream.Filter;
295 output_stream.Filter = value;
299 public Encoding HeaderEncoding {
301 if (headerEncoding == null) {
302 GlobalizationSection gs = WebConfigurationManager.SafeGetSection ("system.web/globalization", typeof (GlobalizationSection)) as GlobalizationSection;
305 headerEncoding = Encoding.UTF8;
307 headerEncoding = gs.ResponseHeaderEncoding;
308 if (headerEncoding == Encoding.Unicode)
309 throw new HttpException ("HeaderEncoding must not be Unicode");
312 return headerEncoding;
316 throw new HttpException ("headers have already been sent");
318 throw new ArgumentNullException ("HeaderEncoding");
319 if (value == Encoding.Unicode)
320 throw new HttpException ("HeaderEncoding must not be Unicode");
321 headerEncoding = value;
325 public NameValueCollection Headers {
328 headers = new HttpHeaderCollection ();
335 public bool IsClientConnected {
337 if (WorkerRequest == null)
338 return true; // yep that's true
340 return WorkerRequest.IsClientConnected ();
344 public bool IsRequestBeingRedirected {
345 get { return is_request_being_redirected; }
348 public TextWriter Output {
353 set { writer = value; }
357 public Stream OutputStream {
359 return output_stream;
363 public string RedirectLocation {
365 return redirect_location;
369 redirect_location = value;
373 public string Status {
374 get { return String.Concat (status_code.ToString (), " ", StatusDescription); }
377 int p = value.IndexOf (' ');
379 throw new HttpException ("Invalid format for the Status property");
381 string s = value.Substring (0, p);
383 if (!Int32.TryParse (s, out status_code))
384 throw new HttpException ("Invalid format for the Status property");
386 status_description = value.Substring (p+1);
390 // We ignore the two properties on Mono as they are for use with IIS7, but there is
391 // no point in throwing PlatformNotSupportedException. We might find a use for them
393 public int SubStatusCode {
398 public bool TrySkipIisCustomErrors {
403 public int StatusCode {
410 throw new HttpException ("headers have already been sent");
413 status_description = null;
417 public string StatusDescription {
419 if (status_description == null)
420 status_description = HttpWorkerRequest.GetStatusDescription (status_code);
422 return status_description;
427 throw new HttpException ("headers have already been sent");
429 status_description = value;
433 public bool SuppressContent {
435 return suppress_content;
439 suppress_content = value;
443 [MonoTODO ("Not implemented")]
444 public void AddCacheDependency (CacheDependency[] dependencies)
446 throw new NotImplementedException ();
449 [MonoTODO ("Not implemented")]
450 public void AddCacheItemDependencies (string[] cacheKeys)
452 throw new NotImplementedException ();
455 [MonoTODO("Currently does nothing")]
456 public void AddCacheItemDependencies (ArrayList cacheKeys)
458 // TODO: talk to jackson about the cache
461 [MonoTODO("Currently does nothing")]
462 public void AddCacheItemDependency (string cacheKey)
464 // TODO: talk to jackson about the cache
467 public void AddFileDependencies (ArrayList filenames)
469 if (filenames == null || filenames.Count == 0)
471 FileDependenciesArray.AddRange (filenames);
474 public void AddFileDependencies (string[] filenames)
476 if (filenames == null || filenames.Length == 0)
478 FileDependenciesArray.AddRange (filenames);
481 public void AddFileDependency (string filename)
483 if (filename == null || filename == String.Empty)
485 FileDependenciesArray.Add (filename);
488 public void AddHeader (string name, string value)
490 AppendHeader (name, value);
493 public void AppendCookie (HttpCookie cookie)
495 Cookies.Add (cookie);
500 // Special case for Content-Length, Content-Type, Transfer-Encoding and Cache-Control
503 public void AppendHeader (string name, string value)
506 throw new HttpException ("Headers have been already sent");
508 if (String.Compare (name, "content-length", true, Helpers.InvariantCulture) == 0){
509 content_length = (long) UInt64.Parse (value);
515 if (String.Compare (name, "content-type", true, Helpers.InvariantCulture) == 0){
521 if (String.Compare (name, "transfer-encoding", true, Helpers.InvariantCulture) == 0){
522 transfer_encoding = value;
528 if (String.Compare (name, "cache-control", true, Helpers.InvariantCulture) == 0){
529 user_cache_control = value;
533 Headers.Add (name, value);
536 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
537 public void AppendToLog (string param)
539 Console.Write ("System.Web: ");
540 Console.WriteLine (param);
543 public string ApplyAppPathModifier (string virtualPath)
545 if (virtualPath == null || context == null)
548 if (virtualPath.Length == 0)
549 return context.Request.RootVirtualDir;
551 if (UrlUtils.IsRelativeUrl (virtualPath)) {
552 virtualPath = UrlUtils.Combine (context.Request.RootVirtualDir, virtualPath);
553 } else if (UrlUtils.IsRooted (virtualPath)) {
554 virtualPath = UrlUtils.Canonic (virtualPath);
557 bool cookieless = false;
558 SessionStateSection config = WebConfigurationManager.GetWebApplicationSection ("system.web/sessionState") as SessionStateSection;
559 cookieless = SessionStateModule.IsCookieLess (context, config);
564 if (app_path_mod != null && virtualPath.IndexOf (app_path_mod) < 0) {
565 if (UrlUtils.HasSessionId (virtualPath))
566 virtualPath = UrlUtils.RemoveSessionId (VirtualPathUtility.GetDirectory (virtualPath), virtualPath);
567 return UrlUtils.InsertSessionId (app_path_mod, virtualPath);
573 public void BinaryWrite (byte [] buffer)
575 output_stream.Write (buffer, 0, buffer.Length);
578 internal void BinaryWrite (byte [] buffer, int start, int len)
580 output_stream.Write (buffer, start, len);
588 public void ClearContent ()
590 output_stream.Clear ();
594 public void ClearHeaders ()
597 throw new HttpException ("headers have been already sent");
599 // Reset the special case headers.
601 content_type = "text/html";
602 transfer_encoding = null;
603 user_cache_control = "private";
604 if (cache_policy != null)
605 cache_policy.Cacheability = HttpCacheability.Private;
611 internal bool HeadersSent {
621 if (WorkerRequest != null)
622 WorkerRequest.CloseConnection ();
626 public void DisableKernelCache ()
628 // does nothing in Mono
636 if (context.TimeoutPossible) {
637 Thread.CurrentThread.Abort (FlagEnd.Value);
639 // If this is called from an async event, signal the completion
641 HttpApplication app_instance = context.ApplicationInstance;
642 if (app_instance != null)
643 app_instance.CompleteRequest ();
650 // Transfer-Encoding (chunked)
653 void AddHeadersNoCache (NameValueCollection write_headers, bool final_flush)
660 write_headers.Add ("Transfer-Encoding", "chunked");
661 else if (transfer_encoding != null)
662 write_headers.Add ("Transfer-Encoding", transfer_encoding);
664 if (redirect_location != null)
665 write_headers.Add ("Location", redirect_location);
668 string vh = VersionHeader;
670 write_headers.Add ("X-AspNet-Version", vh);
673 // If Content-Length is set.
675 if (content_length >= 0) {
676 write_headers.Add (HttpWorkerRequest.GetKnownResponseHeaderName (HttpWorkerRequest.HeaderContentLength),
677 content_length.ToString (Helpers.InvariantCulture));
678 } else if (BufferOutput) {
681 // If we are buffering and this is the last flush, not a middle-flush,
682 // we know the content-length.
684 content_length = output_stream.total;
685 write_headers.Add (HttpWorkerRequest.GetKnownResponseHeaderName (HttpWorkerRequest.HeaderContentLength),
686 content_length.ToString (Helpers.InvariantCulture));
689 // We are buffering, and this is a flush in the middle.
690 // If we are not chunked, we need to set "Connection: close".
693 write_headers.Add (HttpWorkerRequest.GetKnownResponseHeaderName (HttpWorkerRequest.HeaderConnection), "close");
698 // If the content-length is not set, and we are not buffering, we must
702 write_headers.Add (HttpWorkerRequest.GetKnownResponseHeaderName (HttpWorkerRequest.HeaderConnection), "close");
708 // Cache Control, the cache policy takes precedence over the cache_control property.
710 if (cache_policy != null)
711 cache_policy.SetHeaders (this, headers);
713 write_headers.Add ("Cache-Control", CacheControl);
718 if (content_type != null){
719 string header = content_type;
721 if (charset_set || header == "text/plain" || header == "text/html") {
722 if (header.IndexOf ("charset=") == -1) {
723 if (charset == null || charset == "")
724 charset = ContentEncoding.HeaderName;
725 header += "; charset=" + charset;
729 write_headers.Add ("Content-Type", header);
732 if (cookies != null && cookies.Count != 0){
733 int n = cookies.Count;
734 for (int i = 0; i < n; i++)
735 write_headers.Add ("Set-Cookie", cookies.Get (i).GetCookieHeaderValue ());
737 // For J2EE Portal support emulate cookies by storing them in the session.
738 context.Request.SetSessionCookiesForPortal (cookies);
743 internal void WriteHeaders (bool final_flush)
751 if (context != null) {
752 HttpApplication app_instance = context.ApplicationInstance;
753 if (app_instance != null)
754 app_instance.TriggerPreSendRequestHeaders ();
759 if (cached_response != null)
760 cached_response.SetHeaders (headers);
762 // If this page is cached use the cached headers
763 // instead of the standard headers
764 NameValueCollection write_headers;
765 if (cached_headers != null)
766 write_headers = cached_headers;
768 write_headers = Headers;
769 AddHeadersNoCache (write_headers, final_flush);
772 if (WorkerRequest != null)
773 WorkerRequest.SendStatus (status_code, StatusDescription);
775 if (WorkerRequest != null) {
780 for (int i = 0; i < write_headers.Count; i++) {
781 header_name = write_headers.GetKey (i);
782 header_index = HttpWorkerRequest.GetKnownResponseHeaderIndex (header_name);
783 values = write_headers.GetValues (i);
787 foreach (string val in values) {
788 if (header_index > -1)
789 WorkerRequest.SendKnownResponseHeader (header_index, val);
791 WorkerRequest.SendUnknownResponseHeader (header_name, val);
797 internal void DoFilter (bool close)
799 if (output_stream.HaveFilter && context != null && context.Error == null)
800 output_stream.ApplyFilter (close);
803 internal void Flush (bool final_flush)
806 throw new HttpException ("Server cannot flush a completed response");
808 DoFilter (final_flush);
810 if (final_flush || status_code != 200)
814 bool head = ((context != null) && (context.Request.HttpMethod == "HEAD"));
815 if (suppress_content || head) {
818 output_stream.Clear ();
819 if (WorkerRequest != null)
820 output_stream.Flush (WorkerRequest, true); // ignore final_flush here.
824 completed = final_flush;
827 WriteHeaders (final_flush);
829 if (context != null) {
830 HttpApplication app_instance = context.ApplicationInstance;
831 if (app_instance != null)
832 app_instance.TriggerPreSendRequestContent ();
836 cached_response.SetData (output_stream.GetData ());
838 if (WorkerRequest != null)
839 output_stream.Flush (WorkerRequest, final_flush);
847 public void Pics (string value)
849 AppendHeader ("PICS-Label", value);
852 void Redirect (string url, bool endResponse, int code)
855 throw new ArgumentNullException ("url");
858 throw new HttpException ("Headers have already been sent");
860 if (url.IndexOf ('\n') != -1)
861 throw new ArgumentException ("Redirect URI cannot contain newline characters.", "url");
863 is_request_being_redirected = true;
868 url = ApplyAppPathModifier (url);
870 bool isFullyQualified;
871 if (StrUtils.StartsWith (url, "http:", true) ||
872 StrUtils.StartsWith (url, "https:", true) ||
873 StrUtils.StartsWith (url, "file:", true) ||
874 StrUtils.StartsWith (url, "ftp:", true))
875 isFullyQualified = true;
877 isFullyQualified = false;
879 if (!isFullyQualified) {
880 HttpRuntimeSection config = HttpRuntime.Section;
881 if (config != null && config.UseFullyQualifiedRedirectUrl) {
882 var ub = new UriBuilder (context.Request.Url);
883 int qpos = url.IndexOf ('?');
888 ub.Path = url.Substring (0, qpos);
889 ub.Query = url.Substring (qpos + 1);
894 url = ub.Uri.ToString ();
898 redirect_location = url;
900 // Text for browsers that can't handle location header
901 Write ("<html><head><title>Object moved</title></head><body>\r\n");
902 Write ("<h2>Object moved to <a href=\"" + url + "\">here</a></h2>\r\n");
903 Write ("</body><html>\r\n");
907 is_request_being_redirected = false;
910 public void Redirect (string url)
912 Redirect (url, true);
915 public void Redirect (string url, bool endResponse)
917 Redirect (url, endResponse, 302);
920 public void RedirectPermanent (string url)
922 RedirectPermanent (url, true);
925 public void RedirectPermanent (string url, bool endResponse)
927 Redirect (url, endResponse, 301);
930 public void RedirectToRoute (object routeValues)
932 RedirectToRoute ("RedirectToRoute", null, new RouteValueDictionary (routeValues), 302, true);
935 public void RedirectToRoute (RouteValueDictionary routeValues)
937 RedirectToRoute ("RedirectToRoute", null, routeValues, 302, true);
940 public void RedirectToRoute (string routeName)
942 RedirectToRoute ("RedirectToRoute", routeName, null, 302, true);
945 public void RedirectToRoute (string routeName, object routeValues)
947 RedirectToRoute ("RedirectToRoute", routeName, new RouteValueDictionary (routeValues), 302, true);
950 public void RedirectToRoute (string routeName, RouteValueDictionary routeValues)
952 RedirectToRoute ("RedirectToRoute", routeName, routeValues, 302, true);
955 public void RedirectToRoutePermanent (object routeValues)
957 RedirectToRoute ("RedirectToRoutePermanent", null, new RouteValueDictionary (routeValues), 301, false);
960 public void RedirectToRoutePermanent (RouteValueDictionary routeValues)
962 RedirectToRoute ("RedirectToRoutePermanent", null, routeValues, 301, false);
965 public void RedirectToRoutePermanent (string routeName)
967 RedirectToRoute ("RedirectToRoutePermanent", routeName, null, 301, false);
970 public void RedirectToRoutePermanent (string routeName, object routeValues)
972 RedirectToRoute ("RedirectToRoutePermanent", routeName, new RouteValueDictionary (routeValues), 301, false);
975 public void RedirectToRoutePermanent (string routeName, RouteValueDictionary routeValues)
977 RedirectToRoute ("RedirectToRoutePermanent", routeName, routeValues, 301, false);
980 void RedirectToRoute (string callerName, string routeName, RouteValueDictionary routeValues, int redirectCode, bool endResponse)
982 HttpContext ctx = context ?? HttpContext.Current;
983 HttpRequest req = ctx != null ? ctx.Request : null;
986 // Let's emulate .NET
987 throw new NullReferenceException ();
989 VirtualPathData vpd = RouteTable.Routes.GetVirtualPath (req.RequestContext, routeName, routeValues);
990 string redirectUrl = vpd != null ? vpd.VirtualPath : null;
991 if (String.IsNullOrEmpty (redirectUrl))
992 throw new InvalidOperationException ("No matching route found for RedirectToRoute");
994 Redirect (redirectUrl, true, redirectCode);
997 public static void RemoveOutputCacheItem (string path, string providerName)
1000 throw new ArgumentNullException ("path");
1002 if (path.Length > 0 && path [0] != '/')
1003 throw new ArgumentException ("Invalid path for HttpResponse.RemoveOutputCacheItem: '" + path + "'. An absolute virtual path is expected");
1005 OutputCache.RemoveFromProvider (path, providerName);
1008 public static void RemoveOutputCacheItem (string path)
1011 throw new ArgumentNullException ("path");
1013 if (path.Length == 0)
1016 if (path [0] != '/')
1017 throw new ArgumentException ("'" + path + "' is not an absolute virtual path.");
1020 RemoveOutputCacheItem (path, OutputCache.DefaultProviderName);
1022 HttpContext context = HttpContext.Current;
1023 HttpApplication app_instance = context != null ? context.ApplicationInstance : null;
1024 HttpModuleCollection modules = app_instance != null ? app_instance.Modules : null;
1025 OutputCacheModule ocm = modules != null ? modules.Get ("OutputCache") as OutputCacheModule : null;
1026 OutputCacheProvider internalProvider = ocm != null ? ocm.InternalProvider : null;
1027 if (internalProvider == null)
1030 internalProvider.Remove (path);
1034 public void SetCookie (HttpCookie cookie)
1036 AppendCookie (cookie);
1039 public void Write (char ch)
1041 TextWriter writer = Output;
1045 throw new NullReferenceException (".NET 4.0 emulation. A null value was found where an object was required.");
1050 public void Write (object obj)
1052 TextWriter writer = Output;
1056 throw new NullReferenceException (".NET 4.0 emulation. A null value was found where an object was required.");
1061 writer.Write (obj.ToString ());
1064 public void Write (string s)
1066 TextWriter writer = Output;
1070 throw new NullReferenceException (".NET 4.0 emulation. A null value was found where an object was required.");
1075 public void Write (char [] buffer, int index, int count)
1077 TextWriter writer = Output;
1081 throw new NullReferenceException (".NET 4.0 emulation. A null value was found where an object was required.");
1083 writer.Write (buffer, index, count);
1086 bool IsFileSystemDirSeparator (char ch)
1088 return ch == '\\' || ch == '/';
1091 string GetNormalizedFileName (string fn)
1093 if (String.IsNullOrEmpty (fn))
1096 // On Linux we don't change \ to / since filenames with \ are valid. We also
1097 // don't remove drive: designator for the same reason.
1098 int len = fn.Length;
1099 if (len >= 3 && fn [1] == ':' && IsFileSystemDirSeparator (fn [2]))
1100 return Path.GetFullPath (fn); // drive-qualified absolute file path
1102 bool startsWithDirSeparator = IsFileSystemDirSeparator (fn [0]);
1103 if (len >= 2 && startsWithDirSeparator && IsFileSystemDirSeparator (fn [1]))
1104 return Path.GetFullPath (fn); // UNC path
1106 if (!startsWithDirSeparator) {
1107 HttpContext ctx = context ?? HttpContext.Current;
1108 HttpRequest req = ctx != null ? ctx.Request : null;
1111 return req.MapPath (fn);
1114 return fn; // Or should we rather throw?
1117 internal void WriteFile (FileStream fs, long offset, long size)
1119 byte [] buffer = new byte [32*1024];
1122 fs.Position = offset;
1126 while (remain > 0 && (n = fs.Read (buffer, 0, (int) Math.Min (remain, 32*1024))) != 0){
1128 output_stream.Write (buffer, 0, n);
1132 public void WriteFile (string filename)
1134 WriteFile (filename, false);
1137 public void WriteFile (string filename, bool readIntoMemory)
1139 if (filename == null)
1140 throw new ArgumentNullException ("filename");
1142 string fn = GetNormalizedFileName (filename);
1143 if (readIntoMemory){
1144 using (FileStream fs = File.OpenRead (fn))
1145 WriteFile (fs, 0, fs.Length);
1147 FileInfo fi = new FileInfo (fn);
1148 output_stream.WriteFile (fn, 0, fi.Length);
1153 output_stream.ApplyFilter (false);
1158 public void WriteFile (IntPtr fileHandle, long offset, long size) {
1159 throw new PlatformNotSupportedException("IntPtr not supported");
1162 public void WriteFile (IntPtr fileHandle, long offset, long size)
1165 throw new ArgumentNullException ("offset can not be negative");
1167 throw new ArgumentNullException ("size can not be negative");
1172 // Note: this .ctor will throw a SecurityException if the caller
1173 // doesn't have the UnmanagedCode permission
1174 using (FileStream fs = new FileStream (fileHandle, FileAccess.Read))
1175 WriteFile (fs, offset, size);
1179 output_stream.ApplyFilter (false);
1184 public void WriteFile (string filename, long offset, long size)
1186 if (filename == null)
1187 throw new ArgumentNullException ("filename");
1189 throw new ArgumentNullException ("offset can not be negative");
1191 throw new ArgumentNullException ("size can not be negative");
1196 FileStream fs = File.OpenRead (filename);
1197 WriteFile (fs, offset, size);
1202 output_stream.ApplyFilter (false);
1206 public void WriteSubstitution (HttpResponseSubstitutionCallback callback)
1208 // Emulation of .NET behavior
1209 if (callback == null)
1210 throw new NullReferenceException ();
1212 object target = callback.Target;
1213 if (target != null && target.GetType () == typeof (Control))
1214 throw new ArgumentException ("callback");
1216 string s = callback (context);
1222 Cache.Cacheability = HttpCacheability.Server;
1224 if (WorkerRequest == null)
1225 Write (s); // better this than nothing
1227 byte[] bytes = WebEncoding.ResponseEncoding.GetBytes (s);
1228 WorkerRequest.SendResponseFromMemory (bytes, bytes.Length);
1231 cached_response.SetData (callback);
1235 // Like WriteFile, but never buffers, so we manually Flush here
1237 public void TransmitFile (string filename)
1239 if (filename == null)
1240 throw new ArgumentNullException ("filename");
1242 TransmitFile (filename, false);
1245 internal void TransmitFile (string filename, bool final_flush)
1247 FileInfo fi = new FileInfo (filename);
1248 using (Stream s = fi.OpenRead ()); // Just check if we can read.
1249 output_stream.WriteFile (filename, 0, fi.Length);
1250 output_stream.ApplyFilter (final_flush);
1251 Flush (final_flush);
1254 public void TransmitFile (string filename, long offset, long length)
1256 output_stream.WriteFile (filename, offset, length);
1257 output_stream.ApplyFilter (false);
1261 internal void TransmitFile (VirtualFile vf)
1263 TransmitFile (vf, false);
1266 const int bufLen = 65535;
1267 internal void TransmitFile (VirtualFile vf, bool final_flush)
1270 throw new ArgumentNullException ("vf");
1272 if (vf is DefaultVirtualFile) {
1273 TransmitFile (HostingEnvironment.MapPath (vf.VirtualPath), final_flush);
1277 byte[] buf = new byte [bufLen];
1278 using (Stream s = vf.Open ()) {
1280 while ((readBytes = s.Read (buf, 0, bufLen)) > 0) {
1281 output_stream.Write (buf, 0, readBytes);
1282 output_stream.ApplyFilter (final_flush);
1290 #region Session state support
1291 internal void SetAppPathModifier (string app_modifier)
1293 app_path_mod = app_modifier;
1297 #region Cache Support
1298 internal void SetCachedHeaders (NameValueCollection headers)
1300 cached_headers = headers;
1304 internal bool IsCached {
1305 get { return cached_response != null; }
1308 cached_response = new CachedRawResponse (cache_policy);
1310 cached_response = null;
1314 public HttpCachePolicy Cache {
1316 if (cache_policy == null)
1317 cache_policy = new HttpCachePolicy ();
1319 return cache_policy;
1323 internal CachedRawResponse GetCachedResponse ()
1325 if (cached_response != null) {
1326 cached_response.StatusCode = StatusCode;
1327 cached_response.StatusDescription = StatusDescription;
1330 return cached_response;
1334 // This is one of the old ASP compatibility methods, the real cache
1335 // control is in the Cache property, and this is a second class citizen
1337 public string CacheControl {
1339 if (value == null || value == "") {
1340 Cache.SetCacheability (HttpCacheability.NoCache);
1341 user_cache_control = null;
1342 } else if (String.Compare (value, "public", true, Helpers.InvariantCulture) == 0) {
1343 Cache.SetCacheability (HttpCacheability.Public);
1344 user_cache_control = "public";
1345 } else if (String.Compare (value, "private", true, Helpers.InvariantCulture) == 0) {
1346 Cache.SetCacheability (HttpCacheability.Private);
1347 user_cache_control = "private";
1348 } else if (String.Compare (value, "no-cache", true, Helpers.InvariantCulture) == 0) {
1349 Cache.SetCacheability (HttpCacheability.NoCache);
1350 user_cache_control = "no-cache";
1352 throw new ArgumentException ("CacheControl property only allows `public', " +
1353 "`private' or no-cache, for different uses, use " +
1354 "Response.AppendHeader");
1357 get { return (user_cache_control != null) ? user_cache_control : "private"; }
1361 internal int GetOutputByteCount ()
1363 return output_stream.GetTotalLength ();
1366 internal void ReleaseResources ()
1368 if (output_stream != null)
1369 output_stream.ReleaseResources (true);
1381 static class FlagEnd
1383 public static readonly object Value = new object ();