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 if (worker_request.GetHttpVersion () == "HTTP/1.1") {
132 string gatewayIface = context.Request.ServerVariables ["GATEWAY_INTERFACE"];
133 use_chunked = (String.IsNullOrEmpty (gatewayIface) || !gatewayIface.StartsWith ("cgi", StringComparison.OrginalIgnoreCase));
139 writer = new HttpWriter (this);
142 internal TextWriter SetTextWriter (TextWriter writer)
144 TextWriter prev = this.writer;
145 this.writer = writer;
149 internal string VersionHeader {
151 if (!version_header_checked && version_header == null) {
152 version_header_checked = true;
153 HttpRuntimeSection config = HttpRuntime.Section;
154 if (config != null && config.EnableVersionHeader)
155 version_header = Environment.Version.ToString (3);
158 return version_header;
162 internal HttpContext Context {
163 get { return context; }
164 set { context = value; }
167 internal string[] FileDependencies {
169 if (fileDependencies == null || fileDependencies.Count == 0)
170 return new string[0] {};
171 return (string[]) fileDependencies.ToArray (typeof (string));
175 ArrayList FileDependenciesArray {
177 if (fileDependencies == null)
178 fileDependencies = new ArrayList ();
179 return fileDependencies;
193 public bool BufferOutput {
204 // Use the default from <globalization> section if the client has not set the encoding
206 public Encoding ContentEncoding {
208 if (encoding == null) {
209 if (context != null) {
210 string client_content_type = context.Request.ContentType;
211 string parameter = HttpRequest.GetParameter (client_content_type, "; charset=");
212 if (parameter != null) {
214 // Do what the #1 web server does
215 encoding = Encoding.GetEncoding (parameter);
220 if (encoding == null)
221 encoding = WebEncoding.ResponseEncoding;
228 throw new ArgumentException ("ContentEncoding can not be null");
231 HttpWriter http_writer = writer as HttpWriter;
232 if (http_writer != null)
233 http_writer.SetEncoding (encoding);
237 public string ContentType {
243 content_type = value;
247 public string Charset {
250 charset = ContentEncoding.WebName;
261 public HttpCookieCollection Cookies {
264 cookies = new HttpCookieCollection (true, false);
271 if (cache_policy == null)
274 return cache_policy.ExpireMinutes ();
278 Cache.SetExpires (DateTime.Now + new TimeSpan (0, value, 0));
282 public DateTime ExpiresAbsolute {
284 return Cache.Expires;
288 Cache.SetExpires (value);
292 public Stream Filter {
294 if (WorkerRequest == null)
297 return output_stream.Filter;
301 output_stream.Filter = value;
305 public Encoding HeaderEncoding {
307 if (headerEncoding == null) {
308 GlobalizationSection gs = WebConfigurationManager.SafeGetSection ("system.web/globalization", typeof (GlobalizationSection)) as GlobalizationSection;
311 headerEncoding = Encoding.UTF8;
313 headerEncoding = gs.ResponseHeaderEncoding;
314 if (headerEncoding == Encoding.Unicode)
315 throw new HttpException ("HeaderEncoding must not be Unicode");
318 return headerEncoding;
322 throw new HttpException ("headers have already been sent");
324 throw new ArgumentNullException ("HeaderEncoding");
325 if (value == Encoding.Unicode)
326 throw new HttpException ("HeaderEncoding must not be Unicode");
327 headerEncoding = value;
331 public NameValueCollection Headers {
334 headers = new HttpHeaderCollection ();
341 public bool IsClientConnected {
343 if (WorkerRequest == null)
344 return true; // yep that's true
346 return WorkerRequest.IsClientConnected ();
350 public bool IsRequestBeingRedirected {
351 get { return is_request_being_redirected; }
354 public TextWriter Output {
359 set { writer = value; }
363 public Stream OutputStream {
365 return output_stream;
369 public string RedirectLocation {
371 return redirect_location;
375 redirect_location = value;
379 public string Status {
380 get { return String.Concat (status_code.ToString (), " ", StatusDescription); }
383 int p = value.IndexOf (' ');
385 throw new HttpException ("Invalid format for the Status property");
387 string s = value.Substring (0, p);
389 if (!Int32.TryParse (s, out status_code))
390 throw new HttpException ("Invalid format for the Status property");
392 status_description = value.Substring (p+1);
396 // We ignore the two properties on Mono as they are for use with IIS7, but there is
397 // no point in throwing PlatformNotSupportedException. We might find a use for them
399 public int SubStatusCode {
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 (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");
514 if (String.Compare (name, "content-length", true, Helpers.InvariantCulture) == 0){
515 content_length = (long) UInt64.Parse (value);
521 if (String.Compare (name, "content-type", true, Helpers.InvariantCulture) == 0){
527 if (String.Compare (name, "transfer-encoding", true, Helpers.InvariantCulture) == 0){
528 transfer_encoding = value;
534 if (String.Compare (name, "cache-control", true, Helpers.InvariantCulture) == 0){
535 user_cache_control = value;
539 Headers.Add (name, value);
542 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
543 public void AppendToLog (string param)
545 Console.Write ("System.Web: ");
546 Console.WriteLine (param);
549 public string ApplyAppPathModifier (string virtualPath)
551 if (virtualPath == null || context == null)
554 if (virtualPath.Length == 0)
555 return context.Request.RootVirtualDir;
557 if (UrlUtils.IsRelativeUrl (virtualPath)) {
558 virtualPath = UrlUtils.Combine (context.Request.RootVirtualDir, virtualPath);
559 } else if (UrlUtils.IsRooted (virtualPath)) {
560 virtualPath = UrlUtils.Canonic (virtualPath);
563 bool cookieless = false;
564 SessionStateSection config = WebConfigurationManager.GetWebApplicationSection ("system.web/sessionState") as SessionStateSection;
565 cookieless = SessionStateModule.IsCookieLess (context, config);
570 if (app_path_mod != null && virtualPath.IndexOf (app_path_mod) < 0) {
571 if (UrlUtils.HasSessionId (virtualPath))
572 virtualPath = UrlUtils.RemoveSessionId (VirtualPathUtility.GetDirectory (virtualPath), virtualPath);
573 return UrlUtils.InsertSessionId (app_path_mod, virtualPath);
579 public void BinaryWrite (byte [] buffer)
581 output_stream.Write (buffer, 0, buffer.Length);
584 internal void BinaryWrite (byte [] buffer, int start, int len)
586 output_stream.Write (buffer, start, len);
594 public void ClearContent ()
596 output_stream.Clear ();
600 public void ClearHeaders ()
603 throw new HttpException ("headers have been already sent");
605 // Reset the special case headers.
607 content_type = "text/html";
608 transfer_encoding = null;
609 user_cache_control = "private";
610 if (cache_policy != null)
611 cache_policy.Cacheability = HttpCacheability.Private;
617 internal bool HeadersSent {
627 if (WorkerRequest != null)
628 WorkerRequest.CloseConnection ();
632 public void DisableKernelCache ()
634 // does nothing in Mono
642 if (context.TimeoutPossible) {
643 Thread.CurrentThread.Abort (FlagEnd.Value);
645 // If this is called from an async event, signal the completion
647 HttpApplication app_instance = context.ApplicationInstance;
648 if (app_instance != null)
649 app_instance.CompleteRequest ();
656 // Transfer-Encoding (chunked)
659 void AddHeadersNoCache (NameValueCollection write_headers, bool final_flush)
666 write_headers.Add ("Transfer-Encoding", "chunked");
667 else if (transfer_encoding != null)
668 write_headers.Add ("Transfer-Encoding", transfer_encoding);
670 if (redirect_location != null)
671 write_headers.Add ("Location", redirect_location);
674 string vh = VersionHeader;
676 write_headers.Add ("X-AspNet-Version", vh);
679 // If Content-Length is set.
681 if (content_length >= 0) {
682 write_headers.Add (HttpWorkerRequest.GetKnownResponseHeaderName (HttpWorkerRequest.HeaderContentLength),
683 content_length.ToString (Helpers.InvariantCulture));
684 } else if (BufferOutput) {
687 // If we are buffering and this is the last flush, not a middle-flush,
688 // we know the content-length.
690 content_length = output_stream.total;
691 write_headers.Add (HttpWorkerRequest.GetKnownResponseHeaderName (HttpWorkerRequest.HeaderContentLength),
692 content_length.ToString (Helpers.InvariantCulture));
695 // We are buffering, and this is a flush in the middle.
696 // If we are not chunked, we need to set "Connection: close".
699 write_headers.Add (HttpWorkerRequest.GetKnownResponseHeaderName (HttpWorkerRequest.HeaderConnection), "close");
704 // If the content-length is not set, and we are not buffering, we must
708 write_headers.Add (HttpWorkerRequest.GetKnownResponseHeaderName (HttpWorkerRequest.HeaderConnection), "close");
714 // Cache Control, the cache policy takes precedence over the cache_control property.
716 if (cache_policy != null)
717 cache_policy.SetHeaders (this, headers);
719 write_headers.Add ("Cache-Control", CacheControl);
724 if (content_type != null){
725 string header = content_type;
727 if (charset_set || header == "text/plain" || header == "text/html") {
728 if (header.IndexOf ("charset=") == -1) {
729 if (charset == null || charset == "")
730 charset = ContentEncoding.HeaderName;
731 header += "; charset=" + charset;
735 write_headers.Add ("Content-Type", header);
738 if (cookies != null && cookies.Count != 0){
739 int n = cookies.Count;
740 for (int i = 0; i < n; i++)
741 write_headers.Add ("Set-Cookie", cookies.Get (i).GetCookieHeaderValue ());
743 // For J2EE Portal support emulate cookies by storing them in the session.
744 context.Request.SetSessionCookiesForPortal (cookies);
749 internal void WriteHeaders (bool final_flush)
757 if (context != null) {
758 HttpApplication app_instance = context.ApplicationInstance;
759 if (app_instance != null)
760 app_instance.TriggerPreSendRequestHeaders ();
765 if (cached_response != null)
766 cached_response.SetHeaders (headers);
768 // If this page is cached use the cached headers
769 // instead of the standard headers
770 NameValueCollection write_headers;
771 if (cached_headers != null)
772 write_headers = cached_headers;
774 write_headers = Headers;
775 AddHeadersNoCache (write_headers, final_flush);
778 if (WorkerRequest != null)
779 WorkerRequest.SendStatus (status_code, StatusDescription);
781 if (WorkerRequest != null) {
786 for (int i = 0; i < write_headers.Count; i++) {
787 header_name = write_headers.GetKey (i);
788 header_index = HttpWorkerRequest.GetKnownResponseHeaderIndex (header_name);
789 values = write_headers.GetValues (i);
793 foreach (string val in values) {
794 if (header_index > -1)
795 WorkerRequest.SendKnownResponseHeader (header_index, val);
797 WorkerRequest.SendUnknownResponseHeader (header_name, val);
803 internal void DoFilter (bool close)
805 if (output_stream.HaveFilter && context != null && context.Error == null)
806 output_stream.ApplyFilter (close);
809 internal void Flush (bool final_flush)
812 throw new HttpException ("Server cannot flush a completed response");
814 DoFilter (final_flush);
816 if (final_flush || status_code != 200)
820 bool head = ((context != null) && (context.Request.HttpMethod == "HEAD"));
821 if (suppress_content || head) {
824 output_stream.Clear ();
825 if (WorkerRequest != null)
826 output_stream.Flush (WorkerRequest, true); // ignore final_flush here.
830 completed = final_flush;
833 WriteHeaders (final_flush);
835 if (context != null) {
836 HttpApplication app_instance = context.ApplicationInstance;
837 if (app_instance != null)
838 app_instance.TriggerPreSendRequestContent ();
842 cached_response.SetData (output_stream.GetData ());
844 if (WorkerRequest != null)
845 output_stream.Flush (WorkerRequest, final_flush);
853 public void Pics (string value)
855 AppendHeader ("PICS-Label", value);
858 void Redirect (string url, bool endResponse, int code)
861 throw new ArgumentNullException ("url");
864 throw new HttpException ("Headers have already been sent");
866 if (url.IndexOf ('\n') != -1)
867 throw new ArgumentException ("Redirect URI cannot contain newline characters.", "url");
869 is_request_being_redirected = true;
874 url = ApplyAppPathModifier (url);
876 bool isFullyQualified;
877 if (StrUtils.StartsWith (url, "http:", true) ||
878 StrUtils.StartsWith (url, "https:", true) ||
879 StrUtils.StartsWith (url, "file:", true) ||
880 StrUtils.StartsWith (url, "ftp:", true))
881 isFullyQualified = true;
883 isFullyQualified = false;
885 if (!isFullyQualified) {
886 HttpRuntimeSection config = HttpRuntime.Section;
887 if (config != null && config.UseFullyQualifiedRedirectUrl) {
888 var ub = new UriBuilder (context.Request.Url);
889 int qpos = url.IndexOf ('?');
894 ub.Path = url.Substring (0, qpos);
895 ub.Query = url.Substring (qpos + 1);
900 url = ub.Uri.ToString ();
904 redirect_location = url;
906 // Text for browsers that can't handle location header
907 Write ("<html><head><title>Object moved</title></head><body>\r\n");
908 Write ("<h2>Object moved to <a href=\"" + url + "\">here</a></h2>\r\n");
909 Write ("</body><html>\r\n");
913 is_request_being_redirected = false;
916 public void Redirect (string url)
918 Redirect (url, true);
921 public void Redirect (string url, bool endResponse)
923 Redirect (url, endResponse, 302);
926 public void RedirectPermanent (string url)
928 RedirectPermanent (url, true);
931 public void RedirectPermanent (string url, bool endResponse)
933 Redirect (url, endResponse, 301);
936 public void RedirectToRoute (object routeValues)
938 RedirectToRoute ("RedirectToRoute", null, new RouteValueDictionary (routeValues), 302, true);
941 public void RedirectToRoute (RouteValueDictionary routeValues)
943 RedirectToRoute ("RedirectToRoute", null, routeValues, 302, true);
946 public void RedirectToRoute (string routeName)
948 RedirectToRoute ("RedirectToRoute", routeName, null, 302, true);
951 public void RedirectToRoute (string routeName, object routeValues)
953 RedirectToRoute ("RedirectToRoute", routeName, new RouteValueDictionary (routeValues), 302, true);
956 public void RedirectToRoute (string routeName, RouteValueDictionary routeValues)
958 RedirectToRoute ("RedirectToRoute", routeName, routeValues, 302, true);
961 public void RedirectToRoutePermanent (object routeValues)
963 RedirectToRoute ("RedirectToRoutePermanent", null, new RouteValueDictionary (routeValues), 301, false);
966 public void RedirectToRoutePermanent (RouteValueDictionary routeValues)
968 RedirectToRoute ("RedirectToRoutePermanent", null, routeValues, 301, false);
971 public void RedirectToRoutePermanent (string routeName)
973 RedirectToRoute ("RedirectToRoutePermanent", routeName, null, 301, false);
976 public void RedirectToRoutePermanent (string routeName, object routeValues)
978 RedirectToRoute ("RedirectToRoutePermanent", routeName, new RouteValueDictionary (routeValues), 301, false);
981 public void RedirectToRoutePermanent (string routeName, RouteValueDictionary routeValues)
983 RedirectToRoute ("RedirectToRoutePermanent", routeName, routeValues, 301, false);
986 void RedirectToRoute (string callerName, string routeName, RouteValueDictionary routeValues, int redirectCode, bool endResponse)
988 HttpContext ctx = context ?? HttpContext.Current;
989 HttpRequest req = ctx != null ? ctx.Request : null;
992 // Let's emulate .NET
993 throw new NullReferenceException ();
995 VirtualPathData vpd = RouteTable.Routes.GetVirtualPath (req.RequestContext, routeName, routeValues);
996 string redirectUrl = vpd != null ? vpd.VirtualPath : null;
997 if (String.IsNullOrEmpty (redirectUrl))
998 throw new InvalidOperationException ("No matching route found for RedirectToRoute");
1000 Redirect (redirectUrl, true, redirectCode);
1003 public static void RemoveOutputCacheItem (string path, string providerName)
1006 throw new ArgumentNullException ("path");
1008 if (path.Length > 0 && path [0] != '/')
1009 throw new ArgumentException ("Invalid path for HttpResponse.RemoveOutputCacheItem: '" + path + "'. An absolute virtual path is expected");
1011 OutputCache.RemoveFromProvider (path, providerName);
1014 public static void RemoveOutputCacheItem (string path)
1017 throw new ArgumentNullException ("path");
1019 if (path.Length == 0)
1022 if (path [0] != '/')
1023 throw new ArgumentException ("'" + path + "' is not an absolute virtual path.");
1026 RemoveOutputCacheItem (path, OutputCache.DefaultProviderName);
1028 HttpContext context = HttpContext.Current;
1029 HttpApplication app_instance = context != null ? context.ApplicationInstance : null;
1030 HttpModuleCollection modules = app_instance != null ? app_instance.Modules : null;
1031 OutputCacheModule ocm = modules != null ? modules.Get ("OutputCache") as OutputCacheModule : null;
1032 OutputCacheProvider internalProvider = ocm != null ? ocm.InternalProvider : null;
1033 if (internalProvider == null)
1036 internalProvider.Remove (path);
1040 public void SetCookie (HttpCookie cookie)
1042 AppendCookie (cookie);
1045 public void Write (char ch)
1047 TextWriter writer = Output;
1051 throw new NullReferenceException (".NET 4.0 emulation. A null value was found where an object was required.");
1056 public void Write (object obj)
1058 TextWriter writer = Output;
1062 throw new NullReferenceException (".NET 4.0 emulation. A null value was found where an object was required.");
1067 writer.Write (obj.ToString ());
1070 public void Write (string s)
1072 TextWriter writer = Output;
1076 throw new NullReferenceException (".NET 4.0 emulation. A null value was found where an object was required.");
1081 public void Write (char [] buffer, int index, int count)
1083 TextWriter writer = Output;
1087 throw new NullReferenceException (".NET 4.0 emulation. A null value was found where an object was required.");
1089 writer.Write (buffer, index, count);
1092 bool IsFileSystemDirSeparator (char ch)
1094 return ch == '\\' || ch == '/';
1097 string GetNormalizedFileName (string fn)
1099 if (String.IsNullOrEmpty (fn))
1102 // On Linux we don't change \ to / since filenames with \ are valid. We also
1103 // don't remove drive: designator for the same reason.
1104 int len = fn.Length;
1105 if (len >= 3 && fn [1] == ':' && IsFileSystemDirSeparator (fn [2]))
1106 return Path.GetFullPath (fn); // drive-qualified absolute file path
1108 bool startsWithDirSeparator = IsFileSystemDirSeparator (fn [0]);
1109 if (len >= 2 && startsWithDirSeparator && IsFileSystemDirSeparator (fn [1]))
1110 return Path.GetFullPath (fn); // UNC path
1112 if (!startsWithDirSeparator) {
1113 HttpContext ctx = context ?? HttpContext.Current;
1114 HttpRequest req = ctx != null ? ctx.Request : null;
1117 return req.MapPath (fn);
1120 return fn; // Or should we rather throw?
1123 internal void WriteFile (FileStream fs, long offset, long size)
1125 byte [] buffer = new byte [32*1024];
1128 fs.Position = offset;
1132 while (remain > 0 && (n = fs.Read (buffer, 0, (int) Math.Min (remain, 32*1024))) != 0){
1134 output_stream.Write (buffer, 0, n);
1138 public void WriteFile (string filename)
1140 WriteFile (filename, false);
1143 public void WriteFile (string filename, bool readIntoMemory)
1145 if (filename == null)
1146 throw new ArgumentNullException ("filename");
1148 string fn = GetNormalizedFileName (filename);
1149 if (readIntoMemory){
1150 using (FileStream fs = File.OpenRead (fn))
1151 WriteFile (fs, 0, fs.Length);
1153 FileInfo fi = new FileInfo (fn);
1154 output_stream.WriteFile (fn, 0, fi.Length);
1159 output_stream.ApplyFilter (false);
1164 public void WriteFile (IntPtr fileHandle, long offset, long size) {
1165 throw new PlatformNotSupportedException("IntPtr not supported");
1168 public void WriteFile (IntPtr fileHandle, long offset, long size)
1171 throw new ArgumentNullException ("offset can not be negative");
1173 throw new ArgumentNullException ("size can not be negative");
1178 // Note: this .ctor will throw a SecurityException if the caller
1179 // doesn't have the UnmanagedCode permission
1180 using (FileStream fs = new FileStream (fileHandle, FileAccess.Read))
1181 WriteFile (fs, offset, size);
1185 output_stream.ApplyFilter (false);
1190 public void WriteFile (string filename, long offset, long size)
1192 if (filename == null)
1193 throw new ArgumentNullException ("filename");
1195 throw new ArgumentNullException ("offset can not be negative");
1197 throw new ArgumentNullException ("size can not be negative");
1202 FileStream fs = File.OpenRead (filename);
1203 WriteFile (fs, offset, size);
1208 output_stream.ApplyFilter (false);
1212 public void WriteSubstitution (HttpResponseSubstitutionCallback callback)
1214 // Emulation of .NET behavior
1215 if (callback == null)
1216 throw new NullReferenceException ();
1218 object target = callback.Target;
1219 if (target != null && target.GetType () == typeof (Control))
1220 throw new ArgumentException ("callback");
1222 string s = callback (context);
1228 Cache.Cacheability = HttpCacheability.Server;
1230 if (WorkerRequest == null)
1231 Write (s); // better this than nothing
1233 byte[] bytes = WebEncoding.ResponseEncoding.GetBytes (s);
1234 WorkerRequest.SendResponseFromMemory (bytes, bytes.Length);
1237 cached_response.SetData (callback);
1241 // Like WriteFile, but never buffers, so we manually Flush here
1243 public void TransmitFile (string filename)
1245 if (filename == null)
1246 throw new ArgumentNullException ("filename");
1248 TransmitFile (filename, false);
1251 internal void TransmitFile (string filename, bool final_flush)
1253 FileInfo fi = new FileInfo (filename);
1254 using (Stream s = fi.OpenRead ()); // Just check if we can read.
1255 output_stream.WriteFile (filename, 0, fi.Length);
1256 output_stream.ApplyFilter (final_flush);
1257 Flush (final_flush);
1260 public void TransmitFile (string filename, long offset, long length)
1262 output_stream.WriteFile (filename, offset, length);
1263 output_stream.ApplyFilter (false);
1267 internal void TransmitFile (VirtualFile vf)
1269 TransmitFile (vf, false);
1272 const int bufLen = 65535;
1273 internal void TransmitFile (VirtualFile vf, bool final_flush)
1276 throw new ArgumentNullException ("vf");
1278 if (vf is DefaultVirtualFile) {
1279 TransmitFile (HostingEnvironment.MapPath (vf.VirtualPath), final_flush);
1283 byte[] buf = new byte [bufLen];
1284 using (Stream s = vf.Open ()) {
1286 while ((readBytes = s.Read (buf, 0, bufLen)) > 0) {
1287 output_stream.Write (buf, 0, readBytes);
1288 output_stream.ApplyFilter (final_flush);
1296 #region Session state support
1297 internal void SetAppPathModifier (string app_modifier)
1299 app_path_mod = app_modifier;
1303 #region Cache Support
1304 internal void SetCachedHeaders (NameValueCollection headers)
1306 cached_headers = headers;
1310 internal bool IsCached {
1311 get { return cached_response != null; }
1314 cached_response = new CachedRawResponse (cache_policy);
1316 cached_response = null;
1320 public HttpCachePolicy Cache {
1322 if (cache_policy == null)
1323 cache_policy = new HttpCachePolicy ();
1325 return cache_policy;
1329 internal CachedRawResponse GetCachedResponse ()
1331 if (cached_response != null) {
1332 cached_response.StatusCode = StatusCode;
1333 cached_response.StatusDescription = StatusDescription;
1336 return cached_response;
1340 // This is one of the old ASP compatibility methods, the real cache
1341 // control is in the Cache property, and this is a second class citizen
1343 public string CacheControl {
1345 if (value == null || value == "") {
1346 Cache.SetCacheability (HttpCacheability.NoCache);
1347 user_cache_control = null;
1348 } else if (String.Compare (value, "public", true, Helpers.InvariantCulture) == 0) {
1349 Cache.SetCacheability (HttpCacheability.Public);
1350 user_cache_control = "public";
1351 } else if (String.Compare (value, "private", true, Helpers.InvariantCulture) == 0) {
1352 Cache.SetCacheability (HttpCacheability.Private);
1353 user_cache_control = "private";
1354 } else if (String.Compare (value, "no-cache", true, Helpers.InvariantCulture) == 0) {
1355 Cache.SetCacheability (HttpCacheability.NoCache);
1356 user_cache_control = "no-cache";
1358 throw new ArgumentException ("CacheControl property only allows `public', " +
1359 "`private' or no-cache, for different uses, use " +
1360 "Response.AppendHeader");
1363 get { return (user_cache_control != null) ? user_cache_control : "private"; }
1367 internal int GetOutputByteCount ()
1369 return output_stream.GetTotalLength ();
1372 internal void ReleaseResources ()
1374 if (output_stream != null)
1375 output_stream.ReleaseResources (true);
1387 static class FlagEnd
1389 public static readonly object Value = new object ();