前提:
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显示正常 。