1.啟用跨域提交
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Methods" value="GET, POST" /> </customHeaders> </httpProtocol> </system.webServer>
(function () { var domain = 'http://localhost:5000/'; var apiUrl = { getPostOne: function (action) { return domain + 'postone/' + action; }, getOne: function (action) { return domain + 'getone/' + action; } } window.apiUrl = apiUrl; })();
2.Get方式和MVC相同
Get方式前台代碼
/* * 跨域的get請求 * 1個參數 */ $.getJSON(apiUrl.getOne("testone"), { name: 234 }).done(function (data) { alert(data); }); /* * 跨域的get請求 * 2個參數 */ $.get(apiUrl.getOne("TestTwo"), { name: 'abc', age:11 }, function (data) { alert(data); });
Get方式后台代碼
/* * 1.WebApi 控制器方法 默認僅支持一種格式的請求,默認為Post請求 * 2.WebApi 控制器方法 默認不支持Get請求, * 拋出異常:The requested resource does not support http method 'GET'. * 需要手動指定 * FromBody:指定參數來自外部請求 * FromUri:指定參數來自url */ //前台Get請求獲取一個參數 [HttpGet] public string TestOne(string name) { return string.Format("姓名:{0}", name); } //前台Get請求獲取2個參數 [HttpGet] public string TestTwo(string name, int age) { return string.Format("姓名:{0},年齡:{1}", name, age); }
3.POST方式和MVC中不相同,只獲取第一個參數,需要制定 FromBody標志
前台代碼
/* * 跨域的post請求 * 無參數,獲取列表 */ $.post(apiUrl.getOne("PostNull"), { }, function (data) { console.info(data); alert(data[0].name); }); /* * 跨域請求Post * 一個參數,不能指定key的名稱 * 注意參數指定 json 字符串 */ $.post(apiUrl.getOne("PostOne"), { '': '張三' }, function (data) { alert(data); }); /* * 跨域請求Post * 2個參數----失敗 */ $.post(apiUrl.getOne("PostTwo"), { name: '張三' ,age:12}, function (data) { alert(data); }); /* * 跨域請求Post * 1個對象參數 */ $.post(apiUrl.getOne("PostThree"), { name: '張三', age: 12 }, function (data) { alert(data); }); $.ajax({ url: apiUrl.getOne("PostThree"), data: { name: '張三', age: 12 }, type: 'post', success: function (data) { alert(data); } });
對應的后台代碼
/* * 1.WebApi 控制器方法 默認支持Post請求 * 2.默認情況下, * 指定Controller,不指定action時,當前controller中有多種請求方式, * 則:拋出異常,Multiple actions were found that match the request * 3.post方式只能接受一個參數而且必須放在FromBody 里用FromBody特性標識 */ //Post請求無參方法,返回結果json格式 [HttpGet] [HttpPost] public List<object> PostNull() { List<object> list = new List<object>() { new { name="張三"}, new { name="李四",age=11}, }; return list; } //Post請求一個參數 public string PostOne([FromBody] string name) { return string.Format("姓名:{0}", name); } /*Post請求2個參數, * 參與外部交互action中只接受一個參數 * 不支持多個FromBody * 拋出異常:"Can't bind multiple parameters ('name' and 'age') to the request's content." */ public string PostTwo([FromBody] string name, [FromBody] int age) { return string.Format("姓名:{0},年齡:", name, age); } //Post請求 1個 對象參數 public string PostThree([FromBody] Student stu) { return stu.ToString(); }
參考資料: