asp.net关于如何准许api跨域访问

首先需要在原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 + "
";
            }
            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中做配置

原文地址:https://www.cnblogs.com/dushaojun/p/5358525.html