asp.net 一般處理程序(5)-(C#)

           一般處理程序:其實它本質上就是一個類,但是它需要注意幾個方面:j_0015.gif

    (1)需要實現一個IHttpHandler的接口,這是因爲它在asp.net的運行原理中,在創建被請求的頁面類時,需要把它轉成接口,然後再實現接口裏面的Proce***equest()方法;

    (2)裏面還需要實現IsReusable() 的方法,它是表示在服務器上是否可以重用(設置爲true 即爲可重用,一般默認設置爲false)

 

         同時我還簡單利用一般處理程序,寫了一個簡單的計算器,希望和大家一同深入體會一下一般處理程序的運用。

    首先,我是利用Html[作爲前臺]      +     一般處理程序(.ashx)[業務代碼]:

wKiom1L8rZXifrloAABnCWYqv_E060.jpg

        C02index.html代碼:

      

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form action="c02index.ashx" method="post">
<input  type="hidden" name="hidIsPostBack" value="1"/>
<input  type="text" name="txtNum1" value="{num1}"/><select id="Select1" name="Sel">
<option selected="selected">+</option>
<option selected="selected">-</option>
<option selected="selected">*</option>
<option selected="selected">/</option>
</select>
<input  type="text" name="txtNum2" value="{num2}"/>=
<input  type="text" name="txtSum" value="{res}"/><br />
<input  type="submit" value ="計算"/>
</form>
</body>
</html>

     C02index.ashx 一般處理程序的代碼:

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Calulate
{
/// <summary>
/// c02index 的摘要說明
/// </summary>
public class c02index : IHttpHandler
{
public void Proce***equest(HttpContext context)
{
context.Response.ContentType = "text/html";
//1.通過虛擬路徑 獲取絕對路徑
string PhyPath = context.Server.MapPath("c02index.html");
//2.通過絕對路徑獲取文件值
string strHtml = System.IO.File.ReadAllText(PhyPath);
//3.獲取瀏覽器的post方式發過來的參數
string strNum1=context.Request.Form["txtNum1"];
string strNum2=context.Request.Form["txtNum2"];
//4.定義返回的變量
int x=0, y=0, z=0;
//5.判斷接收的參數
if (!string.IsNullOrEmpty(context.Request.Form["hidIsPostBack"]))
{
if(!string.IsNullOrEmpty(strNum1) &&!string.IsNullOrEmpty(strNum2))
{
if(int.TryParse(strNum1,out x) && int.TryParse(strNum2,out y))
{
if (context.Request.Form["Sel"] == "+")
{
z = x + y;
}
else  if (context.Request.Form["Sel"] == "-")
{
z = x - y;
}
else if (context.Request.Form["Sel"] == "*")
{
z = x * y;
}
else if (context.Request.Form["Sel"] == "/")
{
if (y != 0)
{
z = x / y;
}
else
{
throw new Exception("除數不能爲零");
}
}
}
}
//6.替代字符串 並接收替代後的返回值
strHtml = strHtml.Replace("{num1}", x.ToString()).Replace("{num2}", y.ToString()).Replace("{res}", z.ToString());
//7.把字符串返回給瀏覽器
context.Response.Write(strHtml);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

       

 

j_0054.gifj_0054.gifj_0054.gifj_0054.gifj_0054.gifj_0054.gifj_0054.gifj_0054.gifj_0054.gifj_0054.gifj_0054.gifj_0054.gif

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章