使用Cors在WebApi中實現跨域請求
第一步,在webapi項目中安裝cors
在Web API配置文件中(Global.asax)進行全局配置:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
#region 跨域請求
var config = GlobalConfiguration.Configuration;
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
#endregion
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
第二部,代碼編寫
控制器頭部代碼
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class MinderController : ApiController
{
}
返回數據源代碼,請注意,這裏一定不要返回爲字符串。如果返回爲字符串,那麼JSONP的方法不會識別出來,將永遠不會去調用Success方法,我使用的是
public HttpResponseMessage GetMindData(int? CompanyID, int? parent, string callback)
{
Object root = new Object();
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(callback + "(" + JsonConvert.SerializeObject(root) + ")", System.Text.Encoding.UTF8, "text/plain")
};
}
代碼2:改短代碼是使用MVC的方式返回的JSONP數據:
public JavaScriptResult GetMindData(int? CompanyID, string callback)
{
Object root = new Object ();
root.root = company;
string js = callback + "(" + JsonConvert.SerializeObject(root) + ")";
return JavaScript(js);
}
前端的調用:
angular中$http請求JSONP
angular.module('kityminderDemo', ['kityminderEditor'])
.controller('MainController', function ($scope, $http, $sce) {
$scope.initEditor = function (editor, minder) {
window.editor = editor;
window.minder = minder;
/*
$http.get("e.html").then(function (data) { //查詢Use裏的所有數據
window.editor.minder.importData('json', JSON.stringify(data.data));
});
*/
var myUrl = "https://XXX?callback=JSON_CALLBACK";
$sce.trustAsResourceUrl(myUrl);
$http.jsonp(myUrl)
.success(function (response) {
var a = 0;
console.log(response);
window.editor.minder.importData('json', JSON.stringify(response));
}).error(function (e) {
console.log(e);
});
};
});
JS的JSONP請求方式:未經驗證謹慎使用
$.ajax({ url: RESTurl, type: 'GET', dataType: 'jsonp', jsonp: 'callback', jsonpCallback: 'myCallback' }); window.myCallback = function (data) { console.log(data); };