asp.net ashx 学习总结
ashx
一般處理程序(HttpHandler)是·NET眾多web組件的一種,ashx是其擴展名。一個httpHandler接受并處理一個http請求
,類比于Java中的servlet。類比于在Java中需要繼承HttpServlet類。在net中需要實現IHttpHandler接口,這個接口有一
個IsReusable成員,一個待實現的方法ProcessRequest(HttpContextctx) 。程序在processRequest方法中處理接受到的
Http請求。成員IsReusable指定此IhttpHandler的實例是否可以被用來處理多個請求。
.ashx程序適合產生供瀏覽器處理的、不需要回發處理的數據格式,例如用于生成動態圖片、動態文本等內容。
實例
一個httpHandler的實例:
<% @ webhandler language="C#" class="AverageHandler" %>
using System;
using System.Web;
public class AverageHandler : IHttpHandler
{
//IsReusable成員,指定此IhttpHnadler的實例是否可以被用來處理多個請求。
public bool IsReusable{ get { return true; } }
//在processRequest方法中處理http請求
public void ProcessRequest1(HttpContext ctx)
{
ctx.Response.Write("hello");
}
}
在瀏覽器中請求此程序,將會打印hello。
訪問Session
讓自己的ashx類顯式的實現一個接口 IReadOnlySessionState,示例如下:
<% @ webhandler language="C#" class="DownloadHandler" %>
public class DownloadHandler : IHttpHandler, IReadOnlySessionState {
public bool IsReusable { get { return true; }}
public void ProcessRequest2(HttpContext ctx)
{
//在上下文中訪問session
//ctx.Session["fred"]);
}
}
如果要讀寫Session的值,那么只要實現 IRequiresSessionState 接口就即可,這兩個接口沒有待實現的方法。
解決辦法
檢查IIS主目錄->應用程序設置->配置中,有沒有.ashx的后綴;
如果沒有,點擊添加->C:/WINDOWS/Microsoft.NET/Framework/V2.0.50727/aspnet_isapi.dll;
擴展名填入:.ashx
保存即可解決。
========
C# ashx與html的聯合使用
https://www.cnblogs.com/chenyucong/p/5777515.html
本文將介紹ashx和html的聯合使用方法,盡管目前流行mvc,但handler一般處理程序還是ASP.NET的基礎知識,結合html頁
面,做出來的網頁絕對比WebForm的簡潔和效率高。
?
首先,概要說明一下:
html是過去非常老的一種網頁格式,屬于靜態網頁,要想在html上呈現SQL Server上的數據,只能依靠ashx了。
大概的方法是,利用html作為模板,使用ashx讀取數據庫,替換html中的部分內容,最終顯示已替換的html內容。
先給個效果圖:
下面開始上代碼:
首先做用visual studio,新建一個項目,項目下再新建有footer.htm,header.htm,Index.ashx,Index.htm
另外我已做了一個簡單的選取表格信息,顯示在input標簽中的功能,所以我也用到了jquery.min.js
(屏蔽部分請忽略,是我做的另一個靜態頁面,與本例無關)
1、首先看的是Index.htm的靜態網頁代碼:
<!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>
? ? <title>首頁</title>
? ? <style type="text/css">
? ? ? ? body
? ? ? ? {
? ? ? ? ? ? width: 1000px;
? ? ? ? }
? ? ? ? table
? ? ? ? {
? ? ? ? ? ? width: 300px;
? ? ? ? ? ? text-align: center;
? ? ? ? }
? ? ? ? table th
? ? ? ? {
? ? ? ? ? ? text-align: center;
? ? ? ? }
? ? ? ? button
? ? ? ? {
? ? ? ? ? ? background-color: Transparent;
? ? ? ? }
? ? </style>
? ? <script src="jquery-1.8.2.min.js" type="text/javascript"></script>
? ? <script>
? ? function select(obj){
? ? ? ? var $btn=$(obj);
? ? ? ? $("#col1").val($btn.parent().prev().prev().html());
? ? ? ? $("#col2").val($btn.parent().prev().html());
? ? }
? ? </script>
</head>
<body>
? ? $header
? ? <table class="table table-hover" border="1" cellpadding="0px" cellspacing="0px">
? ? ? ? <tr>
? ? ? ? ? ? <th>
? ? ? ? ? ? ? ? col1
? ? ? ? ? ? </th>
? ? ? ? ? ? <th>
? ? ? ? ? ? ? ? col2
? ? ? ? ? ? </th>
? ? ? ? ? ? <th>
? ? ? ? ? ? ? ? col3
? ? ? ? ? ? </th>
? ? ? ? </tr>
? ? ? ? $content
? ? </table>
? ? <br />
? ? <input id="col1" type="text" />
? ? <input id="col2" type="text" />
? ? $footer
</body>
</html>
上圖中,第5行至23行<style>是簡單樣式,
第27行至33行<script>是javascript代碼,用于把table中選中的內容填入到input中,
第37行$header和第55行$footer是頁頭和頁尾的標記,后續會使用另外2個html網頁替換之,
中間的table創建了3個列頭,分別是col1,col2,col3,$content是table的主體部分,后續會在Index.ashx中替換之。
?
2、接著是header.htm:
<h2>
? ? Title
</h2>
footer.htm:
<hr />
CopyRight © XXX
非常的簡單,就是標題和版權信息。
3、最后是Index.ashx:
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.IO;
namespace AshxTest
{
? ? /// <summary>
? ? /// $codebehindclassname$ 的摘要說明
? ? /// </summary>
? ? [WebService(Namespace = "http://tempuri.org/")]
? ? [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
? ? public class Index : IHttpHandler
? ? {
? ? ? ? public void ProcessRequest(HttpContext context)
? ? ? ? {
? ? ? ? ? ? //定義最終響應的文本內容的顯示方式,這里使用html,所以是"text/html"
? ? ? ? ? ? context.Response.ContentType = "text/html";
? ? ? ? ? ? //分別把Index.htm,header.htm,footer.htm中的文本內容賦值給3個string變量,是完整的文本內容
? ? ? ? ? ? //AppDomain.CurrentDomain.BaseDirectory則是指項目的根目錄,由于本例的網頁都放在根目錄下,沒有文
件夾
? ? ? ? ? ? string html = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Index.htm");
? ? ? ? ? ? string header = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "header.htm");
? ? ? ? ? ? string footer = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "footer.htm");
? ? ? ? ? ? //定義table主體內容的string變量為content
? ? ? ? ? ? string content = "";
? ? ? ? ? ? //簡單的for循環10次,把i與abc組合,填入到table的tr td標簽中
? ? ? ? ? ? for (int i = 1; i < 10; i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? content += string.Format("<tr><td>{0}</td><td>{1}</td><td><button value='select'
οnclick='select(this);'>選擇</button></td></tr>", "a" + i, "b" + i);
? ? ? ? ? ? }
? ? ? ? ? ? //以Index.htm的文本內容為基礎,根據標記$header,$content,$footer分別替換上面的3個變量
? ? ? ? ? ? html = html.Replace("$header", header).Replace("$content", content).Replace("$footer", footer);
? ? ? ? ? ? //最終得到的html是完整的html前端代碼,通過context.Response.Write輸出到瀏覽器中
? ? ? ? ? ? context.Response.Write(html);
? ? ? ? }
? ? ? ? public bool IsReusable
? ? ? ? {
? ? ? ? ? ? get
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
注釋都已經加上了,下面看一下運行的效果。
調試Index.htm:
打開后,只有模板的內容:
此時,修改地址欄的后綴名,改為Index.ashx,就會顯示本文開篇時的效果圖了。
(圖中點擊了a8、b8行末端的“選擇”按鈕,在下方的input標簽中顯示"a8"和"b8")
?
結語:
這種制作網頁的方法是最原生態的,是編程人員必須掌握的。
本文只是介紹一個簡單的案例,實際上,在ashx中,可以編寫平常我們寫的C#代碼(包括SQL的操作),在html中也能編寫
javascript,也能使用css樣式,結合form提交和頁面的跳轉,可以完成大部分的網頁功能,本人還沒有學會mvc,所以只
能介紹這種方法了,歡迎各位交流。
========
ashx一般處理程序文件用處
http://www.cnblogs.com/zfanlong1314/p/3501043.html
今天逛博客園,無意發現一篇好文章,關于ashx文件的使用。
文章一:向服務器發送josn字符串,服務器端解析
轉載:http://www.cnblogs.com/yzenet/p/3470388.html
? ? <script type="text/javascript">
? ? ? ? $(function () {
? ? ? ? ? ? $("#btnsave").click(function () {
? ? ? ? ? ? ? ? var json = { "age": 12, "address": "hk",
? ? ? ? ? ? ? ? ? ? "ship": [ { "custID": "sz", "cpname": "bookstrf" },{ "custID": "fkff", "cpname":
"kfg"}]
? ? ? ? ? ? ? ? };
? ? ? ? ? ? ??
? ? ? ? ? ? ? ? $.ajax({
? ? ? ? ? ? ? ? ? ? type: "post",
? ? ? ? ? ? ? ? ? ? url: "Handler/test.ashx",
? ? ? ? ? ? ? ? ? ? datatype: "json",
? ? ? ? ? ? ? ? ? ? data: { name: JSON.stringify(json) },
? ? ? ? ? ? ? ? ? ? async: true,
? ? ? ? ? ? ? ? ? ? success: function (data) {
? ? ? ? ? ? ? ? ? ? ? ? alert(data);
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? });
? ? ? ? ? ? });
? ? ? ? });
? ? </script>
public class test : IHttpHandler
? ? {
? ? ? ? public void ProcessRequest(HttpContext context)
? ? ? ? {
? ? ? ? ??
? ? ? ? ? ? string ss = context.Request["name"];
? ? ? ? ? ? var serialize = new JavaScriptSerializer();
? ? ? ? ? ? var t = serialize.Deserialize<Model>(ss);
? ? ? ? }
? ? ? ? public bool IsReusable
? ? ? ? {
? ? ? ? ? ? get
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? class Model
? ? ? ? {
? ? ? ? ? ? public int age {get; set;}
? ? ? ? ? ? public string address{get; set;}
? ? ? ? ? ? public List<Ship> ship{get; set;}
? ? ? ? }
? ? ? ? class Ship
? ? ? ? {
? ? ? ? ? ? public string custID{get; set;}
? ? ? ? ? ? public string cpname { get; set; }
? ? ? ? }
? ? }
//得到數據對象:
請求URL:http://localhost:3043/Handler1.ashx?name=HelloWorld!
文章二:如何讀取二進制圖片-.ashx一般處理程序 --1?
轉載:http://www.cnblogs.com/travelcai/archive/2007/09/25/904767.html
總結:看了上面文章一和文章二;可以將兩者結合起來。
如果是顯示多個不同圖片時候,是否可以將
?<asp:Image ID="Image1" runat="server" ?ImageUrl="~/ImageHandler.ashx"/></div>
進行改造:
?<asp:Image ID="Image1" runat="server" ?ImageUrl="~/ImageHandler.ashx/?pic=U1513.jpg"/></div>
ashx一般程序代碼:
?
? public void ProcessRequest (HttpContext context)
? ? {
? ? ? ? //獲取虛擬目錄的物理路徑。
? ? ? ? string path = context.Server.MapPath("");
? ? ? ? ?
? ? <strong> ? ?//獲取圖片文件名
? ? ? ? string picFileName = context.Request["pic"];
</strong> ? ? ??
? ? ? ? //獲取圖片文件的二進制數據。
? ? ? ? byte[] datas = System.IO.File.ReadAllBytes(path + "\\" + picFileName);
? ? ? ?//將二進制數據寫入到輸出流中。
? ? ? ? context.Response.OutputStream.Write(datas, 0, datas.Length);
? ? }
? 繼續擴展一下思路:如果是讀取員工信息表,顯示員工頭像呢?是否只需要傳遞EmpID就行呢? 。。。 。。。 。答案
是可以的!!!
========
C# 一般處理程序 ashx文件
?
https://blog.csdn.net/life_is_crazy/article/details/83067950
aspx:Web窗體設計頁面。Web窗體頁由兩部分組成:視覺元素(html、服務器控件和靜態文本)和該頁的編程邏輯(VS中的
設計視圖和代碼視圖可分別看到它們對應得文件)。VS將這兩個組成部分分別存儲在一個單獨的文件中。視覺元素在.aspx
文件中創建
ashx:.ashx文件是主要用來寫web handler的。使用.ashx 可以讓你專注于編程而不用管相關的web技術。我們熟知的.aspx
是要做html控件樹解析的,.aspx包含的所有html實際上是一個類,所有的html都是類里面的成員,這個過程在.ashx是不
需要的。ashx必須包含IsReusable屬性(這個屬性代表是否可復用,通常為true),而如果要在ashx文件用使用Session必
須實現IRequiresSessionState接口.
<%@ WebHandler Language="C#" Class="StockHandler" %>
?
using System;
using System.Web;
using System.Data;
using BLL;
using Comm.Json;
?
public class StockHandler : IHttpHandler
{
? ? DataSet ds = new DataSet();
? ? Mes_ProductBLL mes_ProductBLL = new Mes_ProductBLL();
? ? Mes_MaterialBLL mes_MaterialBLL = new Mes_MaterialBLL();
? ? JSONhelper json = new JSONhelper();
? ? public void ProcessRequest(HttpContext context)
? ? {
? ? ? ? string output = "";
? ? ? ? string action = context.Request["action"].ToString();?
? ? ? ? switch (action)
? ? ? ? {
? ? ? ? ? ? case "GetProductJson":
? ? ? ? ? ? ? ? DataTable pdt = getProductData(context);
? ? ? ? ? ? ? ? string str1 = json.DataTableToJsonWithStringBuilder(pdt);
? ? ? ? ? ? ? ? output = "{\"total\":" + pdt.Rows.Count + ",\"rows\":" + str1 + "}";
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case "GetMaterialJson":
? ? ? ? ? ? ? ? DataTable mdt = getMaterialData(context);
? ? ? ? ? ? ? ? string str2 = json.DataTableToJsonWithStringBuilder(mdt);
? ? ? ? ? ? ? ? output = "{\"total\":" + mdt.Rows.Count + ",\"rows\":" + str2 + "}";
? ? ? ? ? ? ? ? break;
?
? ? ? ? ? ? default:
? ? ? ? ? ? ? ? break;
? ? ? ? }
?
? ? ? ? context.Response.ContentType = "text/plain";
? ? ? ? context.Response.Write(output);
? ? }
? ? /// <summary>
? ? /// 獲取產品數據的放法
? ? /// </summary>
? ? /// <param name="context"></param>
? ? /// <returns></returns>
? ? public DataTable getProductData(HttpContext context)
? ? {
? ? ? ? DataSet ds = new DataSet();
?
? ? ? ? if (context.Request["SerchVale"] != null && !string.IsNullOrEmpty(context.Request
["SerchVale"].ToString()))
? ? ? ? {
? ? ? ? ? ? ds = mes_ProductBLL.GetList(" product_name like '%" + context.Request["SerchVale"].ToString() +
"%'");
? ? ? ? }
? ? ? ? else
? ? ? ? {
? ? ? ? ? ? ds = mes_ProductBLL.GetList("");
? ? ? ? }
? ? ? ? return ds.Tables[0];
? ? }
? ? /// <summary>
? ? /// 獲取原材料數據的方法
? ? /// </summary>
? ? /// <param name="context"></param>
? ? /// <returns></returns>
? ? public DataTable getMaterialData(HttpContext context)
? ? {
? ? ? ? DataSet ds = new DataSet();
?
? ? ? ? if (context.Request["SerchVale"] != null && !string.IsNullOrEmpty(context.Request
["SerchVale"].ToString()))
? ? ? ? {
? ? ? ? ? ? ds = mes_MaterialBLL.GetList(" material_name like '%" + context.Request["SerchVale"].ToString()
+ "%'");
? ? ? ? }
? ? ? ? else
? ? ? ? {
? ? ? ? ? ? ds = mes_MaterialBLL.GetList("");
? ? ? ? }
? ? ? ? return ds.Tables[0];
? ? }
? ? public bool IsReusable
? ? {
? ? ? ? get
? ? ? ? {
? ? ? ? ? ? return false;
? ? ? ? }
? ? }
?
}
ashx特別適合于生成動態圖片,生成動態文本(純文本,json,xml,javascript等即可)等。?
ashx文件有個缺點:它處理控件的回發事件非常麻煩。處理數據的回發,通常都需要一些.aspx頁的功能,只有自己手動處
理這些功能(還不如直接建一個aspx文件來處理)。所以,一般使用.ashx輸出一些不需要回發處理的項目即可。?
========
利用ashx搭建簡易接口
https://blog.csdn.net/ZYD45/article/details/79939475
創建接口的方式有很多,像是Web api,nodejs等等
今天,主要介紹,利用ashx的方式,來搭建一個簡易的api
首先,利用VS編輯器,創建一個空的web應用程序
生成的項目文件
為此程序,添加一個新項,選擇“一般處理程序”,可以看到文件后綴為.ashx
(生成時文件名自定義為APITest)
若是生成后,重命名,不僅只改文件的名字,還要查看標記,更改標記里的信息
然后我們選擇“啟動”,
在生成的localhost網站的url里,增添“/ashx文件名.ashx",就可以看到如下信息
要是想返回json文件,修改下 context.Response.ContentType
然后,返回的信息要組裝成json字符串,
當然.Net也提供了一些轉json的方法,可以自行百度下
context.Response.ContentType = "application/json";
這時候,再去訪問,就可以在瀏覽器的Network中,看到返回的是json對象
要是想解析get方法方法傳過來的參數
string method = context.Request.QueryString["method"];//context.Request.QueryString["Get參數名"]
這時候 method得到的就是“Login”這個值,
要是解析POST方法訪問的參數,用context.Request.Form["POST參數名"]
For Example
前端用,ajax訪問
$.ajax({
?url:'localhost:4883/APITest.ashx?method=Login',
? type:"POST",
? dataType: "json",
? ?data:{password:'123',userID:'Admin'},
? ?success:function(data){
? ? ?console.log(data);//返回的json數據
? },
? error:function(err){
? console.log(err.responseText);//查看錯誤信息
})
ashx想要得到password 和userID就用
string userID=context.Request.Form["userID"];//Admin
string password=context.Request.Form["password";];//123
========
ASHX入門教程
https://www.cnblogs.com/znsongshu/p/6621827.html
新建web應用程序 ?其中添加的ashx包含ashx.CS
普通的web網站只包含ashx
?
新建webapplication應用
新建SampleHandler
public class SampleHandler : IHttpHandler
? ?{
? ? ? ?public void ProcessRequest(HttpContext context)
? ? ? ?{
? ? ? ? ? ?context.Response.ContentType = "text/plain";
? ? ? ? ? ?context.Response.Write("Hello World22222");
? ? ? ?}
?
? ? ? ?public bool IsReusable
? ? ? ?{
? ? ? ? ? ?get
? ? ? ? ? ?{
? ? ? ? ? ? ? ?return false;
? ? ? ? ? ?}
? ? ? ?}
? ?}
添加generichandler
修改handler1
<%@ WebHandler Language="C#" CodeBehind="Handler1.ashx.cs"
Class="WebApplication2.HandlerSample.SampleHandler" %>
以上配置完成后就可以通過“/HandlerSample/Handler1.ashx”訪問了
以下介紹通過更改webconfig配置handler訪問
配置webconfig
<system.webServer>
? ?<defaultDocument> ?配置默認啟動頁
? ? ?<files>
? ? ? ?<add value="Products.aspx" />
? ? ?</files>
? ?</defaultDocument>
? ? ? <handlers>
? ? ? ? <add name="SampleHandler" verb="*" path="handlertest"
type="WebApplication2.HandlerSample.SampleHandler"/>
? ? ? </handlers>
? ? </system.webServer>
瀏覽器輸入***/handlertest就可以直接訪問了
以上兩種訪問方式都可以實現對handler的訪問
總結:只要類實現了IHttpHandler接口,就是一個handler,便可以通過配置ashx或webconfig訪問這個handler
?
發布web application
右鍵你的主啟動項目(一個解決方案多個項目的情況),點擊【發布】
?配置文件:配置文件創建,可以在網上下載,可以自己命名后創建,也可以對已創建的配置文件進行管理(操作比較簡單
這里不做說明)。
?配置文件:命名配置文件
? ?連接:連接設置,選擇(File System,即文件系統)
?連接:發布到的位置選擇,一:到本地文件夾
? ?連接:發布到的位置選擇,二:到IIS
?設置:選擇Release(發布用),Debug(調試用)
預覽:
發布完成后就可以添加到iis當中訪問web application了
訪問站點會出現以下錯誤
解決方法,
到站點目錄的屬性,安全標簽,添加用戶(Everyone),并給修改權限:
========
IIS添加對ashx文件的支持
http://www.cnblogs.com/szytwo/archive/2012/09/04/2670493.html
第一步:每個網站都有個“處理程序映射”,用于添加對各種文件的處理程序
第二步:進入“處理程序映射",可以看到對各種文件的處理程序列表,其中就有對ashx文件的處理
第三步:對應網站的NET版本進行添加對ashx文件的處理,注意:NET是32位還是64位
1、NET4.0環境32位的添加方法,處理程序路徑:%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll
2、NET4.0環境64位的添加方法,處理程序路徑:%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll
========
?
總結
以上是生活随笔為你收集整理的asp.net ashx 学习总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 认识VC++类向导的使用
- 下一篇: Notepad++ 列编辑操作实例二则