.ashx文件

  ashx文件又叫一般处理应用程序,它和aspx文件表面上相差一个字母,前者是h(我想是handler),后者是p(我猜是pages).

  ashx文件处理传入服务器的http请求,可以返回xml,图片,文件,字符串等等。不像aspx文件返回整个页面,这样

当你不需要返回一个页面时,使用ashx文件效率要高。

  下面通过一个例子来看一下:

首先新建一个ashx文件:

Handler1.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication2
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //根据不同响应内容设置context.Response.ContentType
            context.Response.ContentType = "image/jpeg";
            string id = context.Request.QueryString["id"];//获取请求参数
            string dir = "/images/{0}.jpg";
            switch (id)
            {
                case "1":
                    context.Response.WriteFile(context.Server.MapPath(string.Format(dir, "1")));
                    break;
                case "2":
                    context.Response.WriteFile(context.Server.MapPath(string.Format(dir, "2")));
                    break;
                case "3":
                    context.Response.WriteFile(context.Server.MapPath(string.Format(dir, "3")));
                    break;
            }
          
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

然后在同目录images下添加3张图片,新建下面的aspx文件:

WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
</head>
<body>
   
      <form id="form1" runat="server">  
    <div>  
        <div>  
            <img id="img" alt="图片替代文本" src="/images/1.jpg" height="300px" />  
        </div>  
        <a href="#" οnclick="GetImg(1)">1</a>   
        <a href="#" οnclick="GetImg(2)">2</a>   
        <a href="#" οnclick="GetImg(3)">3</a>  
    </div>  
    </form> 




</body>
</html>

<script type="text/javascript" language="javascript">

    function GetImg(index) { //js函数定义形式
        var img = document.getElementById("img");
        img.src = "/Handler1.ashx?id=" + index;
    };



</script>

然后单击2就好切换到第二张图片。

Handler1.ashx文件中有一个content变量,它包含了Request,Response,Server等等对象。

例子出处:http://blog.csdn.net/tcjiaan/article/details/7097180

转载于:https://www.cnblogs.com/wang7/archive/2012/10/23/2735536.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值