First, you need to add the following node (under the <system.webServer> node) to the Web. config in the program of the original API interface
<!--allow cross-domain requests--
Add the following code to the Global.asax in the original API interface program
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear ();
What is the specific reason please own Baidu
Then you need to add the following code to the controller that inherits Apicontroller from the original API
Allow cross-domain request public string Options () { return null;//HTTP. Response with empty body }
Then the project will be released.
Other project calls here are 2 examples, one is the foreground Ajax call, the other is a background call
1. Foreground call
<script src= "/jq/jquery-1.7.min.js" ></script> <script type= "Text/javascript" > Window.onload = function Get () { $.ajax ({ type: ' Get ', URL: '/http '/url '/api/user/getinfo ', dataType: ' JSON ', success:function (data, textstatus) { //alert (data. Uid + "|" + data. UserName + "|" + data. age); }, error:function (XMLHttpRequest, Textstatus, Errorthrown) { } }); } </script>
2. Background calls
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://URL/api/user/getinfo"); Jsondata js = jsonmapper.toobject (t); String name = (string) js["UserName"]; Response.Write (name); return Content (name); }
About Jsondata You also need to add a reference LitJson.dll
In fact, the background calls do not need to add code in the Web. config and controller, can be called directly, but needs to be configured in Global.asax
ASP. NET on how to allow API cross-domain access