前提:
1—開發環境:Win2012+Visual studio2013,dreamweaver CS6, 谷歌瀏覽器。
一、跨域訪問
通過VS2013建立webapi,
1—models類
public class Contact
{
public int ID { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public DateTime Birthday { get; set; }
public int Age { get; set; }
}
2—控制器(數據控制)
public class ContactController : ApiController
{
Contact[] contacts = new Contact[]
{
new Contact(){ID=1,Age=23,Birthday=Convert.ToDateTime("1977-05-30"),Name="情緣",Sex="男" },
new Contact(){ID=2,Age=55,Birthday=Convert.ToDateTime("1937-05-30"),Name="令狐沖",Sex="男" },
new Contact(){ID=3,Age=12,Birthday=Convert.ToDateTime("1987-05-30"),Name="郭靖",Sex="男" },
new Contact(){ID=4,Age=18,Birthday=Convert.ToDateTime("1997-05-30"),Name="黃蓉",Sex="女" },
};
/// <summary>
/// /api/Contact
/// </summary>
/// <returns></returns>
public IEnumerable<Contact> GetListAll()
{
return contacts;
}
public Contact GetContactByID(int id)
{
Contact contact = contacts.FirstOrDefault<Contact>(item => item.ID == id);
if(contact==null){
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return contact;
}
public IEnumerable<Contact> GetListBySex(string sex)
{
return contacts.Where(item => item.Sex == sex);
}
}
3—發佈到本地IIS後
4—寫一個頁面,顯示數據
<!DOCTYPE html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Access-Control_Allow-Origin" content="*" />
<title>webapi跨域訪問</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btnAll").click(function(){
$.getJSON("http://localhost:8013/api/Contact",function(data){
var html="<ul>";
$(data).each(function(i, element) {
html+="<li>"+element.ID+":"+element.Name+":"+element.Sex+"</li>";
});
html+="</ul>";
$("#contactAll").html(html);
});
});
});
</script>
</head>
<body>
<div id="container">
<p>
<input type="button" id="btnAll" value="查詢所有" />
</p>
<p>
<input type="text" id="txtID" name="txtID" />
<input type="button" id="btnID" value="根據ID查詢" />
</p>
<div id="contactAll">
</div>
</div>
</body>
</html>
瀏覽器報錯,跨域訪問。
處理方法: 在webAPI項目中wb.config的段<system.webServer>中增加如下:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<add name="Access-Control-Allow-Headers" value="x-requested-with"/>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
發佈後,Chrome可正常顯示數據。但IE11不能顯示,經度娘號脈,IE8、9默認跨域訪問設置=false。11爲啥也是false?
修改代碼如下:
$("#btnAll").click(function(){
//ajax方法前,設定cors參數,允許跨域訪問
if(!jQuery.support.cors){
jQuery.support.cors=true;
}
$.getJSON("http://localhost:8013/api/Contact",function(data){
var html="<ul>";
$(data).each(function(i, element) {
html+="<li>"+element.ID+":"+element.Name+":"+element.Sex+"</li>";
});
html+="</ul>";
$("#contactAll").html(html);
});
});
IE顯示正常 。