【发布时间】:2011-04-10 08:48:29
【问题描述】:
我正在编写一个 CMS 系统,在阅读并完成了一些示例之后,我决定使用 HttpHandlerFactory 来执行我需要的操作。
关键是我们的网站通常是复制和注册过程的混合体。所以我目前需要使用 aspx 的默认 HttpHandler 来呈现物理注册页面,直到我也能找到一种方法来管理它们。
创建处理程序类后,我将以下内容添加到我网站的网络配置中
<add verb="*" path="*.aspx" type="Web.Helpers.HttpCMSHandlerFactory, Web.Helpers"/>
由于上述路径处理物理和 cms 驱动的页面,通过对代码进行小检查,我可以查看页面是否物理存在,然后可以呈现所需的页面。
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
string pageName = Path.GetFileNameWithoutExtension(context.Request.PhysicalPath);
context.Items.Add("PageName", pageName);
//DirectoryInfo di = new DirectoryInfo(context.Request.MapPath(context.Request.ApplicationPath));
FileInfo fi = new FileInfo(context.Request.MapPath(context.Request.CurrentExecutionFilePath));
//var file = fi.Where(x => string.Equals(x.Name, string.Concat(pageName, ".aspx"), StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();
if (fi.Exists == false)
{
// think I had this the wrong way around, the url should come first with the renderer page second
return PageParser.GetCompiledPageInstance(url, context.Server.MapPath("~/CMSPage.aspx"), context);
}
else
{
return PageParser.GetCompiledPageInstance(context.Request.CurrentExecutionFilePath, fi.FullName, context);
}
}
我的问题是,当有物理页面时,我应该使用PageParser.GetCompiledPageInstance 以外的东西吗?
更新:由于上述我已经继续为图像开发和 HttpHandler,它再次按照相同的原理工作,如果图像存在则使用它,否则从数据库中提供服务。 png 文件有点问题,但以下过程适用于显示的文件格式。
byte[] image = null;
if (File.Exists(context.Request.PhysicalPath))
{
FileStream fs = new FileStream(context.Request.PhysicalPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
image = br.ReadBytes((int)fs.Length);
}
else
{
IKernel kernel = new StandardKernel(new ServiceModule());
var cmsImageService = kernel.Get<IContentManagementService>();
var framework = FrameworkSetup.GetSetFrameworkSettings();
image = cmsImageService.GetImage(Path.GetFileName(context.Request.PhysicalPath), framework.EventId);
}
var contextType = "image/jpg";
var format = ImageFormat.Jpeg;
switch (Path.GetExtension(context.Request.PhysicalPath).ToLower())
{
case ".gif":
contextType = "image/gif";
format = ImageFormat.Gif;
goto default;
case ".jpeg":
case ".jpg":
contextType = "image/jpeg";
format = ImageFormat.Jpeg;
goto default;
case ".png":
contextType = "image/png";
format = ImageFormat.Png;
goto default;
default:
context.Cache.Insert(context.Request.PhysicalPath, image);
context.Response.ContentType = contextType;
context.Response.BinaryWrite(image);
context.Response.Flush();
break;
}
【问题讨论】:
标签: c# asp.net httphandler ihttphandler httphandlerfactory