asp.net關於如何准許api跨域訪問

來源:互聯網
上載者:User

標籤:

首先需要在原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跨域訪問

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.