自定义 httpHandlers
1、在<system.web>下配置
<httpHandlers>
<add verb="GET,HEAD" path="*.vm" type="NVelocityHandler" validate="false" />
</httpHandlers>
2、创建 NVelocityHandler类,代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using Commons.Collections;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
using NVelocity;
/**/
/// <summary>
///
/// </summary>
public class NVelocityHandler : IHttpHandler
{
IHttpHandler Members;
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
// context.Response.Write("测试数据");
VelocityEngine velocity = new VelocityEngine();
ExtendedProperties props = new ExtendedProperties();
//定义模板路径
props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, context.Server.MapPath(""));
//初始化
velocity.Init(props);
List<City> list = new List<City>();
list.Add(new City(21, "sh"));
list.Add(new City(22, "bj"));
list.Add(new City(23, "tj"));
IContext c = new VelocityContext();
//添加到上下文中
c.Put("cities", list);
//根据请求输出
velocity.MergeTemplate("Template/test.vm", "UTF-8", c, context.Response.Output);
}
}
/**/
/// <summary>
/// 城市
/// </summary>
public class City
{
public City(int id, string name)
{
this.id = id;
this.name = name;
}
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
/**/
/// <summary>
/// 名称
/// </summary>
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
3、test.vm在根目录下,其了内容如下:
1##循环输出
2#foreach($city in $cities)
3Id:$city.id<br />
4城市名称:$city.name<br />
5#end
6##索引获取数据
7$cities.get_item(2).name
4、项目中需要引用NVelocity.dll
5、运行项目输入http://主机名/项目名/test.vm 你会惊奇的发现显示的效果。
支持why520crazy的创业产品Worktile
Worktile,新一代简单好用、体验极致的团队协同、项目管理工具,让你和你的团队随时随地一起工作。完全免费,现在就去了解一下吧。
https://worktile.com
Worktile,新一代简单好用、体验极致的团队协同、项目管理工具,让你和你的团队随时随地一起工作。完全免费,现在就去了解一下吧。
https://worktile.com