/// <summary> /// Fill custom url for resizing with image name and extension /// </summary> /// <param name="customResizeUrl">Custom Url with {0} for image url, and {1} for image extension</param> /// <param name="imageUrl">The image to resize</param> /// <returns></returns> public static string GetCustomResizedImageUrl(string customResizeUrl, string imageUrl) { string imageExtension = VirtualPathUtility.GetExtension(Url.PathPart(imageUrl)); string imageUrlWithoutExtension = imageUrl.Replace(imageExtension, string.Empty); return(string.Format(customResizeUrl, imageUrlWithoutExtension, imageExtension)); }
/// <summary> /// 映射当前请求 /// </summary> /// <param name="request">当前 HTTP 请求</param> /// <returns>映射结果</returns> public RequestMapping MapRequest(HttpRequestBase request) { var virtualPath = request.AppRelativeCurrentExecutionFilePath; if (!allowsExtensions.Contains(VirtualPathUtility.GetExtension(virtualPath), StringComparer.InvariantCultureIgnoreCase)) { return(null); } if (!FileExists(virtualPath)) { return(null); } var handlerPath = virtualPath + ".ashx"; if (!FileExists(handlerPath)) { return(null); } var handler = BuildManager.CreateInstanceFromVirtualPath(handlerPath, typeof(JumonyHandler)) as JumonyHandler; if (handler == null) { return(null); } return(new RequestMapping(this, virtualPath, handler)); }
private void LoadSettings() { FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { return; } fileSystem = p.GetFileSystem(); if (fileSystem == null) { return; } if (sourceImagePath.Length > 0) { sourceExists = fileSystem.FileExists(sourceImagePath); ext = VirtualPathUtility.GetExtension(sourceImagePath); } if (resultImagePath.Length > 0) { targetExists = fileSystem.FileExists(resultImagePath); } lblCroppedFileName.Visible = allowUserToChooseCroppedFileName; txtCroppedFileName.Visible = allowUserToChooseCroppedFileName; pnlFinalSize.Visible = allowUserToSetFinalFileSize; if (WebConfigSettings.ImageCropperWrapperDivStyle.Length > 0) { pnlImage.Attributes.Add("style", WebConfigSettings.ImageCropperWrapperDivStyle); } }
public FileSiteMapNode(SiteMapProvider provider, string url) : base(provider, url) { Url = url; Title = VirtualPathUtility.GetFileName(url); FileExtension = VirtualPathUtility.GetExtension(url).TrimStart('.'); }
public static bool IsWebFriendlyImage(HttpPostedFileBase file) { if (file == null) { return(false); } if (file.ContentLength > 2 * 1024 * 1024 || file.ContentLength < 1024) { return(false); } try { foreach (var ext in WebConfigurationManager.AppSettings["validExtensions"].Split(',')) { if (VirtualPathUtility.GetExtension(file.FileName).Contains(ext)) { return(true); } } } catch { return(false); } return(false); }
/// <summary> /// Applies no transformation, but does try to infer the content type if not set /// using the first file in the response (for js and css files only) /// </summary> /// <param name="context"></param> /// <param name="response"></param> public void Process(BundleContext context, BundleResponse response) { if (response == null) { throw new ArgumentNullException("response"); } // No transform done, just set the content type if specified if (!String.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { // Try to infer content type from the bundle files if not specified. if (String.IsNullOrEmpty(response.ContentType) && response.Files != null) { // only set the content type if the first file has a js or css extension BundleFile firstFile = response.Files.FirstOrDefault(); if (firstFile != null) { string extension = VirtualPathUtility.GetExtension(firstFile.VirtualFile.VirtualPath); if (String.Equals(extension, ".js", StringComparison.OrdinalIgnoreCase)) { response.ContentType = JsMinify.JsContentType; } else if (String.Equals(extension, ".css", StringComparison.OrdinalIgnoreCase)) { response.ContentType = CssMinify.CssContentType; } } } } }
/// <summary> /// 读取 ASPX 页面所呈现的 HTML 内容 /// </summary> /// <param name="context">当前 HTTP 请求</param> /// <param name="virtualPath">ASPX 文件路径</param> /// <returns>ASPX 页面所呈现的 HTML 内容</returns> public HtmlContentResult LoadContent(HttpContextBase context, string virtualPath) { if (context == null) { throw new ArgumentNullException("context"); } if (!VirtualPathUtility.IsAppRelative(virtualPath)) { return(null); } if (!allowsExtensions.Contains(VirtualPathUtility.GetExtension(virtualPath))) { return(null); } using (var writer = new StringWriter()) { context.Server.Execute(virtualPath, writer, false); return(new HtmlContentResult(this, writer.ToString(), new Uri(context.Request.Url, VirtualPathUtility.ToAbsolute(virtualPath)))); } }
private void LogEvent(object sender, EventArgs e, string name, StreamWatcher watcher) { try { if (((HttpApplication)sender).Context.Request.CurrentExecutionFilePathExtension.ToLower() == ".aspx") { HttpApplication app = (HttpApplication)sender; HttpContext context = app.Context; string filePath = context.Request.FilePath; string fileExtension = VirtualPathUtility.GetExtension(filePath); var page = (Page)context.CurrentHandler; Log($"HttpModuleTest_{name}", context, page, null, watcher); } if (((HttpApplication)sender).Context.Request.CurrentExecutionFilePathExtension.ToLower() == ".ashx") { HttpApplication app = (HttpApplication)sender; HttpContext context = app.Context; string filePath = context.Request.FilePath; string fileExtension = VirtualPathUtility.GetExtension(filePath); var handler = (IHttpHandler)context.CurrentHandler; Log($"HttpModuleTest_Handler_{name}", context, null, handler, watcher); } } catch (Exception ex) { } }
private static string GetMimeTypeFromExtension(string path) { switch (VirtualPathUtility.GetExtension(path.ToLower())) { case ".css": return("text/css"); case ".gif": return("image/gif"); case ".jpg": case ".jpeg": return("image/jpeg"); case ".js": return("text/javascript"); case ".pdf": return("application/pdf"); case ".png": return("image/png"); case ".txt": return("text/plain"); default: return("application/octet-stream"); } }
public void Start() { var staticFileExtensions = configFactory.Sections.Web.Vpp.Zips.StaticFileExtensions.OfType <string>().ToList(); foreach (var vppElement in configFactory.Sections.Web.Vpp.Zips.AllElements) { string filePath = vppElement.FilePath; string observedPath = vppElement.ObservedPath; string path = MapPath(filePath); if (!File.Exists(path)) { Trace.TraceWarning("Did not find configured (" + vppElement.Name + ") zip vpp on disk: " + path); continue; } DateTime lastModified = File.GetLastWriteTimeUtc(path); var vpp = new Ionic.Zip.Web.VirtualPathProvider.ZipFileVirtualPathProvider(path); Trace.WriteLine("Registering VPP: " + vpp); Register(vpp); broker.PostResolveAnyRequestCache += (s, a) => { var application = s as HttpApplication; var context = application.Context; var requestPath = context.Request.AppRelativeCurrentExecutionFilePath; if (!requestPath.StartsWith(observedPath, StringComparison.InvariantCultureIgnoreCase)) { return; } if (!vpp.DirectoryExists(VirtualPathUtility.GetDirectory(requestPath))) { return; } string extension = VirtualPathUtility.GetExtension(requestPath).ToLower(); if (extension == "") { requestPath = requestPath.TrimEnd('/') + "/Default.aspx"; //context.RewritePath(requestPath.TrimEnd('/') + "/Default.aspx"); } // There's a problem with RouteTable.Routes keeping storing the default vpp before we register our vpp, in which case // RouteExistingFiles will not handle files in the zip vpp. This is a workaround. if (extension == "" || extension == ".aspx" || extension == ".axd" || extension == ".ashx") { if (vpp.FileExists(requestPath)) { var handler = System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(requestPath, typeof(IHttpHandler)); context.RemapHandler(handler as IHttpHandler); } } else if (staticFileExtensions.Contains(extension) && vpp.FileExists(requestPath)) { context.RemapHandler(new VirtualPathFileHandler() { Modified = lastModified }); } }; } }
private void MoveFile(HttpContext context) { var result = OpResult.Denied; if ( (fileSystem.Permission.IsExtAllowed(VirtualPathUtility.GetExtension(virtualSourcePath))) && (fileSystem.Permission.IsExtAllowed(VirtualPathUtility.GetExtension(virtualTargetPath))) ) { try { if (OnFileMoving(virtualSourcePath, virtualTargetPath, ref result)) { result = fileSystem.MoveFile(virtualSourcePath, virtualTargetPath, false); } } catch (Exception ex) { log.Error(ex); result = OpResult.Error; } } RenderJsonResult(context, result); }
private void Application_BeginRequest(Object source, EventArgs e) { // Create HttpApplication and HttpContext objects to access // request and response properties. HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; string filePath = context.Request.FilePath; string fileExtension = VirtualPathUtility.GetExtension(filePath); string ipAddress = context.Request.UserHostAddress; if (fileExtension.Equals(".aspx")) { context.Response.Write("<h1><font color=red>" + "HelloWorldModule: Beginning of Request" + "</font></h1><hr>"); // context.Response.Write("ipaddress" + ipAddress); } //checking for valid ipaddress if (IsValidIpAddress(ipAddress)) { //returning 403 status code context.Response.StatusCode = 403; // (Forbidden) } }
public void UploadFile(int uid, int pid) { if (HttpContext.Current.Request.Files.Count > 0) { try { foreach (var fileName in HttpContext.Current.Request.Files.AllKeys) { HttpPostedFile file = HttpContext.Current.Request.Files[fileName]; if (file != null) { FileDTO dto = new FileDTO(); dto.Name = file.FileName; dto.FileExt = VirtualPathUtility.GetExtension(file.FileName); dto.UploadedOn = DateTime.Now; dto.CreatedBy = uid; dto.ParentFolderId = pid; dto.UniqueName = Guid.NewGuid().ToString(); dto.FileSizeInKB = file.ContentLength / 1024; dto.ContentType = file.ContentType; var rootPath = HttpContext.Current.Server.MapPath("~/UploadedFiles"); var fileSavePath = System.IO.Path.Combine(rootPath, dto.UniqueName + dto.FileExt); file.SaveAs(fileSavePath); FileBO.Save(dto); } } } catch (Exception e) { } } }
void context_BeginRequest(object sender, EventArgs e) { HttpApplication context = sender as HttpApplication; bool needCheck = false; var checkers = IocInstance.Container.ResolveOptional <IEnumerable <IProtectedAssetChecker> >(); if (checkers != null && checkers.Count() > 0) { foreach (var c in checkers) { if (c.IsProtectedAsset(context.Request.Url)) { needCheck = true; break; } } } if (needCheck) { var filters = IocInstance.Container.ResolveOptional <IEnumerable <IAssetProtectionFilter> >(); if (filters != null && filters.Count() > 0) { foreach (var f in filters) { if (f.AllowAccess(context.Context) == false) { var ext = VirtualPathUtility.GetExtension(context.Request.FilePath); string path = string.Format("~/Content/errors/403" + ext); context.Server.TransferRequest(path); } } } } }
/// <summary>Returns true if the requested resource is one of the typical resources that needn't be processed by the cms engine.</summary> /// <param name="sender">The event sender, probably a http application.</param> /// <returns>True if the request targets a static resource file.</returns> /// <remarks> /// These are the file extensions considered to be static resources: /// .css /// .gif /// .png /// .jpg /// .jpeg /// .js /// .axd /// .ashx /// </remarks> protected static bool IsStaticResource(object sender) { HttpApplication application = sender as HttpApplication; if (application != null) { string path = application.Request.Path; string extension = VirtualPathUtility.GetExtension(path); if (extension == null) { return(false); } switch (extension.ToLower()) { case ".css": case ".gif": case ".png": case ".jpg": case ".jpeg": case ".js": case ".axd": case ".ashx": return(true); } } return(false); }
private void application_AuthenticateRequest(Object source, EventArgs e) { HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; string filePath = context.Request.FilePath.ToString().ToLower(); string fileName = VirtualPathUtility.GetFileName(filePath); string fileExt = VirtualPathUtility.GetExtension(filePath); string rawUrl = context.Request.RawUrl.ToLower(); if (fileExt.CompareTo(".aspx") != 0) { if (rawUrl.Contains("/files/qr/")) { context.Response.Redirect("/web/web_login.aspx"); return; } return; } if (rawUrl.Contains("/web/") && !rawUrl.Contains("/web/web_login.aspx") && !rawUrl.Contains("/web/web_ajax.aspx")) { if (!WebLoginHelper.IsLogin()) { context.Response.Redirect("/web/web_login.aspx"); return; } return; } }
public override void Write(ContentItem item, string propertyName, TextWriter writer) { string url = item[propertyName] as string; if (string.IsNullOrEmpty(url)) { return; } string extension = VirtualPathUtility.GetExtension(url); switch (ImagesUtility.GetExtensionGroup(extension)) { case ImagesUtility.ExtensionGroups.Images: base.Write(item, propertyName, writer); return; case ImagesUtility.ExtensionGroups.Flash: WriteFlash(url, writer); return; case ImagesUtility.ExtensionGroups.Video: WriteMovie(url, writer); return; case ImagesUtility.ExtensionGroups.Audio: WriteAudio(url, writer); return; } }
/// <summary> /// Returns true if the requested resource is one of the typical resources that needn't be processed. /// </summary> /// <param name="sender">The event sender, probably a http application.</param> /// <returns>True if the request targets a static resource file.</returns> /// <remarks> /// These are the file extensions considered to be static resources: /// .css /// .gif /// .png /// .jpg /// .jpeg /// .js /// </remarks> public static bool IsStaticResource(HttpRequest request) { if (request != null) { string extension = VirtualPathUtility.GetExtension(request.Path); if (string.IsNullOrEmpty(extension)) { return(false); } extension = extension.ToLower(); if (extension == ".aspx") { return(false); } string allowExtensions = AreaConfig.Instance["allowExtensions"]; if (!string.IsNullOrEmpty(allowExtensions) && allowExtensions.Contains(extension)) { return(false); } } return(true); }
public virtual bool IsVirtualDir(string virtualPath) { /* * Se o path possuir extension, ignora. * Se o path for reservado, ignora. */ try { var extension = VirtualPathUtility.GetExtension(virtualPath); if (!string.IsNullOrEmpty(extension)) { return(false); } var path = VirtualPathUtility .RemoveTrailingSlash(VirtualPathUtility.ToAbsolute(virtualPath) .ToLowerInvariant()); if (!string.IsNullOrEmpty(path)) { if (_ignoredDirectories.Any(path.Contains)) { return(false); } } return(true); } catch (Exception ex) { Trace.TraceInformation("IsVirtualDir", ex); } return(false); }
public void Write(ContentItem item, string propertyName, TextWriter writer) { string url = item[propertyName] as string; if (string.IsNullOrEmpty(url)) { return; } string extension = VirtualPathUtility.GetExtension(url); switch (extension.ToLower()) { case ".gif": case ".png": case ".jpg": case ".jpeg": DisplayableImageAttribute.WriteImage(item, propertyName, PreferredSize, alt, CssClass, writer); return; default: WriteUrl(item, propertyName, cssClass, writer, url); return; } }
/// <summary> /// Returns true if the requested resource is one of the typical resources that needn't be processed by the cms engine. /// </summary> /// <param name="request">HTTP Request</param> /// <returns>True if the request targets a static resource file.</returns> /// <remarks> /// These are the file extensions considered to be static resources: /// .css /// .gif /// .png /// .jpg /// .jpeg /// .js /// .axd /// .ashx /// </remarks> public virtual bool IsStaticResource(HttpRequest request) { if (request == null) { throw new ArgumentNullException("request"); } string path = request.Path; string extension = VirtualPathUtility.GetExtension(path); if (extension == null) { return(false); } switch (extension.ToLower()) { case ".axd": case ".ashx": case ".bmp": case ".css": case ".gif": case ".ico": case ".jpeg": case ".jpg": case ".js": case ".png": case ".rar": case ".zip": return(true); } return(false); }
public void ProcessRequest(HttpContext context) { //UrlDecode is neccessary to compensate encoding in ImageAdapter string imageUrl = HttpUtility.UrlDecode(context.Request["img"]); string w = context.Request["w"]; string h = context.Request["h"]; string m = context.Request["m"]; double width = 0; double.TryParse(w, out width); double height = 0; double.TryParse(h, out height); ImageResizeMode mode; switch (m) { case "Fill": mode = ImageResizeMode.Fill; break; case "Stretch": mode = ImageResizeMode.Stretch; break; default: mode = ImageResizeMode.Fit; break; } IFileSystem fs = N2.Context.Current.Resolve <IFileSystem>(); if (fs.FileExists(imageUrl)) { string path = context.Server.MapPath(imageUrl); if (CacheUtility.IsModifiedSince(context.Request, path)) { CacheUtility.NotModified(context.Response); } context.Response.ContentType = "image/jpeg"; string extension = VirtualPathUtility.GetExtension(imageUrl); ImageResizer ir = N2.Context.Current.Resolve <ImageResizer>(); CacheUtility.SetValidUntilExpires(context.Response, TimeSpan.FromDays(7)); using (var s = fs.OpenFile(imageUrl)) { var resized = ir.GetResizedBytes(s, extension, width, height, mode); context.Response.BinaryWrite(resized); } } else { throw new HttpException(404, "Not found"); } }
/// <summary> /// 尝试获取指定地址 HTML 文档的文档对象提供程序 /// </summary> /// <param name="virtualPath">HTML 文档虚拟路径</param> /// <returns>若添加了 HtmlDocumentProvider 设置,并能将文档编译为 IHtmlDocumentProvider 对象,则返回,否则返回 null</returns> public static IHtmlDocumentProvider TryGetDocumentProvider(string virtualPath) { if (failedHtmlProviders.Contains(virtualPath)) { return(null); } var section = WebConfigurationManager.GetSection("system.web/compilation", virtualPath) as CompilationSection; if (section == null) { return(null); } if (section.BuildProviders[VirtualPathUtility.GetExtension(virtualPath)] == null) { return(null); } try { var provider = BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(IHtmlDocumentProvider)) as IHtmlDocumentProvider; if (provider != null) { return(provider); } } catch { } failedHtmlProviders.Add(virtualPath); return(null); }
public static string ParseRazor(string sourceRazor, string virtualPath, bool throws = false) { try { var extension = VirtualPathUtility.GetExtension(virtualPath); if (extension.IsEmpty() || extension != ".cshtml") { return(string.Empty); } Trace.TraceInformation("Parsing razor... {0}", virtualPath); var host = WebRazorHostFactory.CreateHostFromConfig(virtualPath); string code = GenerateCodeFromRazorString(host, sourceRazor, virtualPath); return(code); } catch (Exception ex) { Trace.TraceInformation("Error:... {0}", ex.Message); if (throws) { throw; } return(ex.Message); } }
public static bool IsWebFriendlyAttachment(HttpPostedFileBase file) { if (file == null) { return(false); } if (file.ContentLength > 2 * 1024 * 1024 || file.ContentLength < 1024) { return(false); } try { var fileExt = VirtualPathUtility.GetExtension(file.FileName); return(fileExt.Contains(".bmp") || fileExt.Contains(".png") || fileExt.Contains(".jpg") || fileExt.Contains(".jpeg") || fileExt.Contains(".tiff") || fileExt.Contains(".pdf") || fileExt.Contains(".txt") || fileExt.Contains(".doc") || fileExt.Contains(".docx") || fileExt.Contains(".xls") || fileExt.Contains(".xlsx")); } catch { return(false); } }
public bool IsStaticResource(HttpRequestBase request) { Condition.Requires(request).IsNotNull(); var extension = VirtualPathUtility.GetExtension(request.Path); if (extension == null) { return(false); } switch (extension.ToLower()) { case ".axd": case ".ashx": case ".bmp": case ".css": case ".gif": case ".ico": case ".jpeg": case ".jpg": case ".js": case ".png": case ".rar": case ".zip": return(true); } return(false); }
void context_BeginRequest(object sender, EventArgs e) { if (_Extenstions.Count() > 0) { string ext = VirtualPathUtility.GetExtension(_context.Request.FilePath). Substring(1).ToLower(); if (_Extenstions.Contains(ext)) { _IsMatch = true; } } if (_Files.Count() > 0) { string fileName = VirtualPathUtility.GetFileName(_context.Request.FilePath).ToLower(); if (_Files.Contains(fileName)) { _IsMatch = true; } } if (_LogAlwaysRequest || _IsMatch) { StreamReader reader = new StreamReader(_context.Request.InputStream); string requestText = reader.ReadToEnd(); _context.Request.InputStream.Position = 0; //LOG requestText } }
private void Application_EndRequest(Object source, EventArgs e) { if (Statsd != null) { var application = (HttpApplication)source; var context = application.Context; var filePath = context.Request.FilePath; var fileExtension = VirtualPathUtility.GetExtension(filePath); if (fileExtension != null && fileExtension.Equals(".aspx")) { var stopwatch = (Stopwatch)context.Items[StopwatchKey]; stopwatch.Stop(); var hasException = false; if (context.Error != null) { hasException = true; Statsd.LogCount("exceptions", GetRouteData(context, hasException)); } Statsd.LogCount("request", GetRouteData(context, hasException)); Statsd.LogTiming("responses", stopwatch.ElapsedMilliseconds, GetRouteData(context, hasException)); } } }
public void ProcessRequest(HttpContext context) { switch (VirtualPathUtility.GetExtension(context.Request.Url.AbsolutePath)) { case ".eot": Transmit(context, "application/x-eot"); return; case ".svg": Transmit(context, "image/svg+xml"); return; case ".ttf": Transmit(context, "application/x-ttf"); return; case ".woff": Transmit(context, "application/font-woff"); return; case ".otf": Transmit(context, "application/x-otf"); return; } }
public override void Write(ContentItem item, string propertyName, TextWriter writer) { var filePath = item[propertyName] as string; if (string.IsNullOrEmpty(filePath)) { return; } string url = Context.Current.Container.Resolve <IExternalWebLinkResolver>().GetPublicUrl(filePath); if (string.IsNullOrWhiteSpace(url)) { return; } var extension = VirtualPathUtility.GetExtension(url); switch (ImagesUtility.GetExtensionGroup(extension)) { case ImagesUtility.ExtensionGroups.Images: writer.Write("<img src=\"{0}\" alt=\"{1}\" />", url, Alt); return; default: writer.Write("<a href=\"{0}\">{1}</a>", url, VirtualPathUtility.GetFileName(url)); return; } }