支持Ajax跨域訪問(wèn)ASP.NET Web Api 2(Cors)的示例教程
隨著深入使用ASP.NET Web Api,我們可能會(huì)在項(xiàng)目中考慮將前端的業(yè)務(wù)分得更細(xì)。比如前端項(xiàng)目使用Angularjs的框架來(lái)做UI,而數(shù)據(jù)則由另一個(gè)Web Api 的網(wǎng)站項(xiàng)目來(lái)支撐。注意,這里是兩個(gè)Web網(wǎng)站項(xiàng)目了,前端項(xiàng)目主要負(fù)責(zé)界面的呈現(xiàn)和一些前端的相應(yīng)業(yè)務(wù)邏輯處理,而Web Api則負(fù)責(zé)提供數(shù)據(jù)。
這樣問(wèn)題就來(lái)了,如果前端通過(guò)ajax訪問(wèn)Web Api項(xiàng)目話,就涉及到跨域了。我們知道,如果直接訪問(wèn),正常情況下Web Api是不允許這樣做的,這涉及到安全問(wèn)題。所以,今天我們這篇文章的主題就是討論演示如何配置Web Api以讓其支持跨域訪問(wèn)(Cors)。好了,下面我們以一個(gè)簡(jiǎn)單的示例直接進(jìn)入本文的主題。
首先打開Visual Studio 2013,創(chuàng)建一個(gè)空白的解決方案,命名為:CrossDomainAccessWebAPI。
再創(chuàng)建一個(gè)空的Web Api項(xiàng)目,命名為:CrossDomainAccess.WebAPI

接著我們右鍵單擊剛才創(chuàng)建的解決方案,創(chuàng)建一個(gè)空的Web項(xiàng)目用來(lái)模擬我們的網(wǎng)站對(duì)WebAPI項(xiàng)目進(jìn)行跨域調(diào)用,如下:

完成以上步驟以后,我們的解決方案目錄如下圖所示:

下面我們?cè)谀M網(wǎng)站的Web項(xiàng)目中通過(guò)Nuget添加jQuery,一下是添加jQuery包的界面:

添加完成后,到這里我們就完成了前期的準(zhǔn)備工作。下面在WebAPI項(xiàng)目的Models文件夾中添加是一個(gè)實(shí)體類UserInfo,具體代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CrossDomainAccess.WebAPI.Models
{
public class UserInfo
{
public int Id { get; set; }
public string UserName { get; set; }
public string UserPass { get; set; }
public string Email { get; set; }
public DateTime RegTime { get; set; }
}
}
然后在WebAPI項(xiàng)目中添加一個(gè)示例控制器:UserInfoController,這個(gè)控制器用來(lái)返回?cái)?shù)據(jù)集合,具體代碼如下:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using CrossDomainAccess.WebAPI.Models;
namespace CrossDomainAccess.WebAPI.Controllers
{
public class UserInfoController : ApiController
{
/// <summary>
/// 獲取用戶信息集合的方法
/// </summary>
/// <returns>返回用戶信息集合</returns>
public IHttpActionResult GetList()
{
//對(duì)象集合模擬數(shù)據(jù)
List<UserInfo> list = new List<UserInfo>()
{
new UserInfo()
{
Id = 1,
UserName = "張三",
UserPass = "FDASDFAS",
Email = "zhangsan@163.com",
RegTime = DateTime.Now
},
new UserInfo()
{
Id = 2,
UserName = "李四",
UserPass = "FDASDFAS",
Email = "lisi@163.com",
RegTime = DateTime.Now
},
new UserInfo()
{
Id = 3,
UserName = "王五",
UserPass = "FDASDFAS",
Email = "wangwu@163.com",
RegTime = DateTime.Now
},
new UserInfo()
{
Id = 4,
UserName = "趙六",
UserPass = "FDASDFAS",
Email = "zhaoliu@163.com",
RegTime = DateTime.Now
},
new UserInfo()
{
Id = 5,
UserName = "田七",
UserPass = "FDASDFAS",
Email = "tianqi@163.com",
RegTime = DateTime.Now
},
new UserInfo()
{
Id = 6,
UserName = "王八",
UserPass = "FDASDFAS",
Email = "wangba@163.com",
RegTime = DateTime.Now
}
};
return Ok(list);
}
}
}
接著我們需要修改一下App_Start目錄下的WebApiConfig.cs文件中webapi的路由規(guī)則,以便通過(guò)api/{controller}/{action}的方式進(jìn)行訪問(wèn),同時(shí)讓修改序列化方式,讓W(xué)ebAPI默認(rèn)輸出json格式的數(shù)據(jù),具體操作如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
namespace CrossDomainAccess.WebAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服務(wù)
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//清除所有序列化格式
config.Formatters.Clear();
//添加Json格式的序列化器
config.Formatters.Add(new JsonMediaTypeFormatter());
}
}
}
重新生成一下項(xiàng)目,并在瀏覽器中訪問(wèn),這時(shí)我們可以的到j(luò)son格式的數(shù)據(jù),如下:
好了,到這里我們Web Api端的數(shù)據(jù)輸出就準(zhǔn)備好了。為了測(cè)試是否可以跨域訪問(wèn),我們?cè)俎D(zhuǎn)到CorsDemo.UI網(wǎng)站項(xiàng)目中。首先創(chuàng)建一個(gè)index.aspx頁(yè)面(這個(gè)命名自己可以任意取)后打開,修改成如下的代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="CrossDomainAccess.Web.Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="Scripts/jquery-2.2.3.min.js"></script>
<script type="text/javascript">
$(function () {
$('#getData').click(function () {
$.ajax({
url: 'http://localhost:29867/api/UserInfo/getlist',
dataType: 'json',
success: function (data) {
//以表格的形式在瀏覽器控制臺(tái)顯示數(shù)據(jù),IE下不支持
console.table(data);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="跨域獲取數(shù)據(jù)" id="getData" />
</div>
</form>
</body>
</html>
完成以上步驟以后,啟動(dòng)WebAPI項(xiàng)目和Web項(xiàng)目,并在Web項(xiàng)目的Index頁(yè)面中點(diǎn)擊跨域獲取數(shù)據(jù)按鈕,打開瀏覽器控制臺(tái)查看請(qǐng)求結(jié)果,在控制臺(tái)會(huì)出現(xiàn)如下結(jié)果:

控制臺(tái)提示我們跨域請(qǐng)求被阻止,同時(shí)提示CORS頭部信息確實(shí),所以我們可以通過(guò)去WebAPI配置CORS來(lái)讓其支持跨域訪問(wèn)。
那現(xiàn)在我們?cè)赪ebAPI項(xiàng)目中通過(guò)Nuget添加Microsoft.AspNet.WebApi.Cors ,然后在WebApiConfig.cs文件中配置HttpConfiguration的EnableCors方法即可。具體操作如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CrossDomainAccess.WebAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服務(wù)
EnableCrossSiteRequests(config);
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//清除所有序列化格式
config.Formatters.Clear();
//添加Json格式的序列化器
config.Formatters.Add(new JsonMediaTypeFormatter());
}
/// <summary>
/// 允許跨域調(diào)用
/// </summary>
/// <param name="config"></param>
private static void EnableCrossSiteRequests(HttpConfiguration config)
{
//對(duì)所有的請(qǐng)求來(lái)源沒(méi)有任何限制
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*"
);
config.EnableCors(cors);
}
}
}
現(xiàn)在,我們?cè)僦匦律蒞ebAPI項(xiàng)目并運(yùn)行,接著在頁(yè)面http://localhost:31521/Index.aspx中點(diǎn)擊按鈕“跨域獲取數(shù)據(jù)”,通過(guò)firebug的控制臺(tái),我們可以看到數(shù)據(jù)跨域加載成功了,如下:

更多精彩內(nèi)容,請(qǐng)點(diǎn)擊《ajax跨域技術(shù)匯總》,進(jìn)行深入學(xué)習(xí)和研究。
至此,關(guān)于ASP.Net Web Api支持跨域請(qǐng)求的示例和演示就完成了,謝謝大家的閱讀。
相關(guān)文章
.net控件dropdownlist動(dòng)態(tài)綁定數(shù)據(jù)具體過(guò)程分解
一、在頁(yè)面初始化時(shí)候?qū)⒓辖壎ǖ紻ropDownList;二、在頁(yè)面初始化的時(shí)候向DropDownList添加數(shù)據(jù);三、將DataReader讀取的數(shù)據(jù)動(dòng)態(tài)綁定到DropDownList等等2013-05-05
ASP.NET Core3.1 Ocelot路由的實(shí)現(xiàn)
這篇文章主要介紹了ASP.NET Core3.1 Ocelot路由的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
.net6?在中標(biāo)麒麟下的安裝和部署過(guò)程
這篇文章主要介紹了.net6?在中標(biāo)麒麟下的安裝部署,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04
ASP.NET也像WinForm程序一樣運(yùn)行的實(shí)現(xiàn)方法
我們今天要談到的是讓ASP.NET的程序也像WinForm一樣的運(yùn)行,這樣就不需要安裝IIS或者Visual Studio這樣的特定環(huán)境了2012-01-01
.net 通過(guò)URL推送POST數(shù)據(jù)具體實(shí)現(xiàn)
這篇文章主要介紹了.net 通過(guò)URL推送POST數(shù)據(jù)具體實(shí)現(xiàn),有需要的朋友可以參考一下2013-12-12

