.ashx 文件用于寫(xiě)web handler的。.ashx文件與.aspx文件類似,可以通過(guò)它來(lái)調(diào)用HttpHandler類,它免去了普通.aspx頁(yè)面的控件解析以及頁(yè)面處理的過(guò)程。其實(shí)就是帶HTML和C#的混合文件。
.ashx文件適合產(chǎn)生供瀏覽器處理的、不需要回發(fā)處理的數(shù)據(jù)格式,例如用于生成動(dòng)態(tài)圖片、動(dòng)態(tài)文本等內(nèi)容。很多需要用到此種處理方式。此文檔提供一個(gè)簡(jiǎn)單的調(diào)用ashx文件的Demo,并貼出關(guān)鍵文件的源碼。
public class Login : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";
//GET方式獲取傳遞的數(shù)據(jù)
//string username = context.Request.QueryString["username"];
//string password = context.Request.QueryString["password"];
//POST方式獲取傳遞的數(shù)據(jù)
string username = context.Request.Form["username"];
string password = context.Request.Form["password"];
string message = null;
if (string.IsNullOrEmpty(username))
{
message = "用戶名不能為空";
context.Response.Write("{"success":false,"message":"" + message + ""}");//此JSON格式非常重要,否則會(huì)執(zhí)行jquery的的error函數(shù)
context.Response.End();
}
if (string.IsNullOrEmpty(password))
{
message = "密碼不能為空";
context.Response.Write("{"success":false,"message":"" + message + ""}");
context.Response.End();
}
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
if (username.ToUpper() == "ADMIN" && password == "123")
{
message = "登錄成功";
context.Response.Write("{"success":true,"message":"" + message + ""}");
}
else
{
message = "用戶名或密碼錯(cuò)誤";
context.Response.Write("{"success":false,"message":"" + message + ""}");
}
}
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
<!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>jsquery訪問(wèn)ashx文件</title>
<script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script language="javascript" type="text/javascript">
function login() {
$.ajax({
url: 'common/handler/Login.ashx',
type: 'POST',
data: { 'username': $("#txtUsername").val(), 'password': $("#txtPassword").val() },
dataType: 'json',
timeout: 50000,
//contentType: 'application/json;charset=utf-8',
success: function (response) {
alert(response.message);
},
error: function (err) {
alert("執(zhí)行失敗");
}
});
}
</script>
</head>
<body>
<div style="width:400px; height:300px; margin:0 auto; background:#c0c0c0;">
<dl style=" width:270px;">
<dd><span>用戶名:</span><input type="text" style=" width:150px;" id="txtUsername" /></dd>
<dd><span>密 碼:</span><input type="password" style=" width:150px;" id="txtPassword" /></dd>
<dd><input type="button" style=" width:65px; height:23px; float:right;" onclick="login()" value="登錄" /></dd>
</dl>
</div>
</body>
</html>