標籤:
首先需要在原api介面的程式中在web.config添加如下節點(在<system.webServer>節點下)
<!--准許跨域請求--> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> </customHeaders> </httpProtocol>
在原api介面程式中的Global.asax中添加如下代碼
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
具體是什麼原因請自行百度
然後需要在原api繼承ApiController的控制器中添加如下代碼
//准許跨域請求 public string Options() { return null; // HTTP 200 response with empty body }
然後該項目發布就可以了
其它項目調用的時候這裡舉2個例子,一個是前台ajax調用,一個是後台調用
1.前台調用
<script src="/jq/jquery-1.7.min.js"></script> <script type="text/javascript"> window.onload = function get() { $.ajax({ type: ‘GET‘, url: ‘http://網址/api/user/getInfo‘, dataType: ‘json‘, success: function (data, textStatus) { //alert(data.Uid + " | " + data.UserName + "|" + data.Age); }, error: function (xmlHttpRequest, textStatus, errorThrown) { } }); } </script>
2.後台調用
public static string request(string url) { string strURL = url; System.Net.HttpWebRequest request; request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); request.Method = "GET"; System.Net.HttpWebResponse response; response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream s; s = response.GetResponseStream(); string StrDate = ""; string strValue = ""; StreamReader Reader = new StreamReader(s, Encoding.UTF8); while ((StrDate = Reader.ReadLine()) != null) { strValue += StrDate + "\r\n"; } return strValue; }
protected void Page_Load(object sender, EventArgs e) { string t = request("http://網址/api/user/getInfo"); JsonData js = JsonMapper.ToObject(t); String name = (String)js["UserName"]; Response.Write(name); //return Content(name); }
關於JsonData這裡還需要添加一個引用LitJson.dll
其實後台調用的話不需要在web.config和控制器中添加代碼,直接就能調用,但需要在Global.asax中做配置
asp.net關於如何准許api跨域訪問