1 // Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. 2 3 using System.Globalization; 4 using System.Web.WebPages.Resources; 5 using Microsoft.Internal.Web.Utils; 6 7 namespace System.Web.WebPages.ApplicationParts 8 { 9 // Used to serve static resource files (e.g. .jpg, .css, .js) that live inside appliaction modules 10 internal class ResourceHandler : IHttpHandler 11 { 12 private readonly string _path; 13 private readonly ApplicationPart _applicationPart; 14 ResourceHandler(ApplicationPart applicationPart, string path)15 public ResourceHandler(ApplicationPart applicationPart, string path) 16 { 17 if (applicationPart == null) 18 { 19 throw new ArgumentNullException("applicationPart"); 20 } 21 22 if (String.IsNullOrEmpty(path)) 23 { 24 throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "path"); 25 } 26 27 _applicationPart = applicationPart; 28 _path = path; 29 } 30 31 public bool IsReusable 32 { 33 get { return true; } 34 } 35 ProcessRequest(HttpContext context)36 public void ProcessRequest(HttpContext context) 37 { 38 ProcessRequest(new HttpResponseWrapper(context.Response)); 39 } 40 ProcessRequest(HttpResponseBase response)41 internal void ProcessRequest(HttpResponseBase response) 42 { 43 string virtualPath = _path; 44 45 // Make sure it starts with ~/ 46 if (!virtualPath.StartsWith("~/", StringComparison.Ordinal)) 47 { 48 virtualPath = "~/" + virtualPath; 49 } 50 51 // Get the resource stream for this virtual path 52 using (var stream = _applicationPart.GetResourceStream(virtualPath)) 53 { 54 if (stream == null) 55 { 56 throw new HttpException(404, String.Format( 57 CultureInfo.CurrentCulture, 58 WebPageResources.ApplicationPart_ResourceNotFound, _path)); 59 } 60 61 // Set the mime type based on the file extension 62 response.ContentType = MimeMapping.GetMimeMapping(virtualPath); 63 64 // Copy it to the response 65 stream.CopyTo(response.OutputStream); 66 } 67 } 68 } 69 } 70