http://dotnet.aspx.cc/article/3e52138f-17ba-479a-84d6-765411e5a7fe/read.aspx
AJAX(XMLHttpRequest)進行跨域請求方法詳解(三)
3,帶驗證信息的請求
身份驗證是Web開發中經常遇到的問題,在跨域請求中,默認情況下是不發送驗證信息的。要想發送驗證信息,需要進行withCredentials 屬性,下面就是一個簡單請求的例子:
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>孟憲會之AJAX跨域請求測試</title>
</head>
<body>
<input type='button' value='開始測試' onclick='crossDomainRequest()' />
<div id="content"></div>
<script type="text/javascript">
//<![CDATA[
var xhr = new XMLHttpRequest();
var url = 'http://dotnet.aspx.cc/RequestsWithCredentials.aspx';
function crossDomainRequest() {
document.getElementById("content").innerHTML = "開始進行請求……";
if (xhr) {
xhr.open('GET', url, true);
xhr.onreadystatechange = handler;
xhr.withCredentials = "true";
xhr.send();
} else {
document.getElementById("content").innerHTML = "不能創建 XMLHttpRequest。";
}
}
function handler(evtXHR) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = xhr.responseText;
document.getElementById("content").innerHTML = "結果:" + response;
} else {
document.getElementById("content").innerHTML += "<br/>執行狀態 status:" + xhr.status;
}
}
else {
document.getElementById("content").innerHTML += "<br/>執行狀態 readyState:" + xhr.readyState;
}
}
//]]>
</script>
</body>
</html>
在服務器端,我編寫如下的代碼,通過 Cookie 記錄按鈕點擊的次數:
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod.Equals("GET"))
{
Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");
Response.AddHeader("Access-Control-Allow-Credentials", "true");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Expires = -1;
int visit = 1;
if (Request.Cookies["visit"] != null)
{
visit = Convert.ToInt32(Request.Cookies["visit"].Value) + 1;
}
HttpCookie cookie = new HttpCookie("visit", visit.ToString());
cookie.Expires = DateTime.Now.AddSeconds(30);
Response.SetCookie(cookie);
Response.Write(visit.ToString());
}
else if (Request.HttpMethod.Equals("OPTIONS"))
{
//可以根據Origin進行更多檢測
//通知客戶端允許預檢請求。並設置緩存時間
Response.ClearContent();
Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");
Response.AddHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
Response.AddHeader("Access-Control-Allow-Credentials", "true");
Response.AddHeader("Access-Control-Max-Age", "30");
//此過程無需返回數據
Response.End();
}
else
{
Response.StatusCode = 401;
}
}
</script>
點擊“開始測試”,我們可以檢測到下面的請求執行過程:
Host: dotnet.aspx.cc
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/RequestsWithCredentials.html
Origin: http://www.meng_xian_hui.com:801
HTTP/1.x 200 OK
Date: Sun, 10 Jan 2010 14:12:26 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
Access-Control-Allow-Credentials: true
Set-Cookie: ASP.NET_SessionId=fn2zf0zq1cuwgf45fm5fw145; path=/; HttpOnly
Set-Cookie: visit=1; expires=Sun, 10-Jan-2010 14:12:56 GMT; path=/
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: text/html; charset=utf-8
Content-Length: 1
從上面的響應中可以看出,Cookie 是會隨響應一起發送的。如果我們多次點擊測試按鈕,則可以看到請求和響應的結果是這樣的:
Host: dotnet.aspx.cc
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/RequestsWithCredentials.html
Origin: http://www.meng_xian_hui.com:801
Cookie: ASP.NET_SessionId=fn2zf0zq1cuwgf45fm5fw145; visit=2
HTTP/1.x 200 OK
Date: Sun, 10 Jan 2010 14:13:58 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
Access-Control-Allow-Credentials: true
Set-Cookie: visit=3; expires=Sun, 10-Jan-2010 14:14:28 GMT; path=/
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: text/html; charset=utf-8
Content-Length: 1
注意 Cookie: ASP.NET_SessionId=fn2zf0zq1cuwgf45fm5fw145; visit=2 這一行,訪問計數器已經被一起發送到服務器。