ashx文件的使用小结
一提到ashx文件,我们就会想到http handler以及图片加载(在之前我们一般使用aspx或者webservice去做),一般做法如下:
handler.ashx:
<%@ webhandler language="c#" class="handler" %>
using system;
using system.io;
using system.web;
public class handler : ihttphandler {
public bool isreusable {
get {
return true;
}
}
public void processrequest (httpcontext context) {
context.response.contenttype = "image/jpeg";
context.response.cache.setcacheability(httpcacheability.public);
context.response.bufferoutput = false;
photosize size;
switch (context.request.querystring["size"]) {
case "s":
size = photosize.small;
break;
case "m":
size = photosize.medium;
break;
case "l":
size = photosize.large;
break;
default:
size = photosize.original;
break;
}
int32 id = -1;
stream stream = null;
if (context.request.querystring["photoid"] != null && context.request.querystring["photoid"] != "") {
id = convert.toint32(context.request.querystring["photoid"]);
stream = photomanager.getphoto(id, size);
} else {
id = convert.toint32(context.request.querystring["albumid"]);
stream = photomanager.getfirstphoto(id, size);
}
if (stream == null) stream = photomanager.getphoto(size);
const int buffersize = 1024 * 16;
byte[] buffer = new byte[buffersize];
int count = stream.read(buffer, 0, buffersize);
while (count > 0) {
context.response.outputstream.write(buffer, 0, count);
count = stream.read(buffer, 0, buffersize);
}
}
}
*.aspx:
<img src="myhttphander.ashx?id=123" width="20" height="20" />
我们变通以下,发现其实除了可以输出图片以外,还可以输出文字:
handler.ashx:
<%@ webhandler language="c#" class="handler" %>
using system;
using system.web;
public class handler : ihttphandler {
public void processrequest (httpcontext context) {
context.response.contenttype = "text/plain";
context.response.write("alert('hi')");
}
public bool isreusable {
get {
return false;
}
}
}
*.aspx:
弹出alert
<script src="handler.ashx"></script>
也可以把.ashx当成css文件
<link href="css/handler.ashx" rel="stylesheet" type="text/css">
xml文件
orderdoc.load("handler.ashx");
还可以嵌入文字:
handler.ashx:
<%@ webhandler language="c#" class="testhandler" %>
using system;
using system.web;
public class testhandler : ihttphandler {
public void processrequest (httpcontext context) {
context.response.contenttype = "text/plain";
context.response.write("document.write(\"hello world\");");
}
public bool isreusable {
get {
return false;
}
}
}
*.aspx:
<script type="text/javascript" src="testhandler.ashx" />
当你希望从ashx或httphandler里访问你的session时,你必须实现ireadonlysessionstate接口.
代码:
using system;
using system.web;
using system.web.sessionstate;
public class downloadhandler : ihttphandler, ireadonlysessionstate
{
public bool isreusable { get { return true; } }
public void processrequest(httpcontext ctx)
{
ctx.response.write(ctx.session["fred"]);
}
}
其实,学习的思路不应该这样,以上除了图片外,我们都用偏了,为什么用偏了呢,因为软件以简单、实用为主,我们只是把以上纯粹看成可一项技术而没有把它放到软件的地位去考虑:)
具体的用途,大家可以参考rewirte.dll (这个dll,可以使服务器支持伪静态的)
上一篇: spring中ioc是什么
下一篇: java异常机制分析