由於 web api 項目通常是被做成了一個獨立站點,來提供數據,在做web api 項目的時候,不免前端會遇到跨域訪問接口的問題。
剛開始沒做任何處理,用jsonp的方式調用 web api 接口,總是報一個錯誤,如下:

如果你想用JSONP來獲得跨域的數據,WebAPI本身是不支持javascript的callback的,它返回的JSON是這樣的:
{"YourSignature":"嫁人要嫁程序員,錢多話少死得早"}
然而,JSONP請求期望得到這樣的JSON:
jQuery123456([{"YourSignature":"嫁人要嫁程序員,錢多話少死得早"}])
所以我們需要對WebAPI做拓展,讓它支持這樣的callback
解決方案如下:
只需要給全局注冊一個JsonCallbackAttribute,就可以判斷接口的訪問是屬於跨域,還是非跨域,正常的返回。
因為我們的接口,可能是用來給 移動端(Android 、IOS)做數據接口,也有可能是給網站用,所以,考慮到可能存在跨域的問題。
GlobalConfiguration.Configuration.Filters.Add(new JsonCallbackAttribute());
public class JsonCallbackAttribute : ActionFilterAttribute { private const string CallbackQueryParameter = "callback"; public override void OnActionExecuted(HttpActionExecutedContext context) { var callback = string.Empty; if (IsJsonp(out callback)) { var jsonBuilder = new StringBuilder(callback); jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result); context.Response.Content = new StringContent(jsonBuilder.ToString()); //context.Response.Content = new StringContent("C(\"a\")"); } base.OnActionExecuted(context); } private bool IsJsonp(out string callback) { callback = System.Web.HttpContext.Current.Request.QueryString[CallbackQueryParameter]; return !string.IsNullOrEmpty(callback); }
結合下面圖片不難開出,請求的地址帶回了,callback的參數標識。

測試代碼如下:
<html>
<head>
<title>團隊信息列表</title>
<script type="text/javascript" src="@Url.Content("~/scripts/jquery-1.7.1.js")"></script>
</head>
<body>
<ul id="contacts"></ul>
<script type="text/javascript">
$(function () {
$.ajax({
Type: "GET",
url: "http://app.uni2uni.com/api/CloudService/GetAllGroup",
dataType: "jsonp",
success: listContacts
});
});
function listContacts(contacts) {
alert(contacts);
$.each(contacts.data, function (index, contact) {
var html = "<li><ul>";
html += "<li>GroupName: " + contact.GroupName + "</li>";
html += "<li>GroupPicture:" + contact.GroupPicture + "</li>";
html += "</ul>";
$("#contacts").append($(html));
});
}
</script>
</body>
</html>
返回接口如下:

相關文章推薦:http://diaosbook.com/Post/2013/12/27/tips-for-aspnet-webapi-cors
