【.ashx 文件】
Asp.Net常用文件【牛腩】
我的这篇博客中做过相关介绍,就不过多阐述了… 在这篇博客的基础上,继续了解.ashx文件的作用。
【代码片段】
<%@ WebHandler Language="C#" Class="First" %>
using System;
using System.Web;
using System.Text;
public class First : IHttpHandler {
//请求过来找到一般处理程序文件,自动执行processRequest方法
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/html";//指定返回给浏览器的数据类型
context.Response.Write("Hello World");//将字符串返回给浏览器
StringBuilder sb = new StringBuilder();
sb.Append("<table border='1'><tr><td>用户名</td><td>itcast</td></tr>");
sb.Append("<tr><td>密码</td><td>123</td></tr></table>");
context.Response.Write(sb.ToString());
}
public bool IsReusable {
get {
return false;
}
}
}
效果:
【.html模板文件】
通过上面的“小栗子”我们发现,如果想改变.ashx 呈现的样式,在.ashx改起来相当的麻烦。更何况,关于样式,应该是美工要做的事情,那么我们就可以创建一个.html模板文件。
.html模板文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<table>
<tr><td>用户名</td><td>$name</td></tr>
<tr><td>密码</td><td>$pwd</td></tr>
</table>
</body>
</html>
.ashx 文件
<%@ WebHandler Language="C#" Class="Show" %>
using System;
using System.Web;
using System.IO;
public class Show : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/html";
//获取要操作的模板路径
string filePath = context.Request.MapPath("ShowInfo.html");//获取文件的物理路径。在Asp.net中,对文件或文件夹的操作一定要获取物理路径
//读取模板文件中的内容
string fileContent = File.ReadAllText(filePath);
//用户具体的数据替换模板文件中的占位符
fileContent = fileContent.Replace("$name", "itcast").Replace("$pwd", "123");
//将替换后的内容输出给浏览器
context.Response.Write(fileContent);
}
这样,当我们在想改动动态网页的样式的时候,就可以直接在模板文件上改动了。也就是Asp.Net常用文件【牛腩】博客中写到的.ashx文件的作用:使用.ashx 可以让你专注于编程而不用管相关的WEB技术。