.net asp 实现json 格式跨域访问 的方法

在<configuration> 配置目录下添加允许跨域的头部信息

//webapi 默认的web.config有配置
//1)删除 下面参数  否者WEB API 会 出现405 错误   没有此配置可直接第二步 ↓
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>


//2)添加配置//
 <system.webServer>

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
        <add name="Access-Control-Allow-Headers" value="X-PINGOTHER, Content-Type,X-Requested-With"/>
        <add name="Access-Control-Allow-Origin" value="*" />

//需要回传cooki 
<add name="Access-Control-Allow-Credentials" value="true"/>
<add name="withCredentials" value="true"/>
      </customHeaders>
    </httpProtocol>







  </system.webServer>

[System.Web.Services.WebMethod]//声明调用的方法

    public static bool Test(string word)

{

return ture;

}

//回传格式 joson '{d:"返回数据"}'

jq post 数据方法



                var params = '{name:"' + 'a' + '"}'; // name 参数名 调用的函数对应的名字 ,与静态函数的传参名相同
                $.ajax({
                    url: "http://localhost:57437/del.aspx/Test",  //调用后台方法  Test
                    data: params,
                    type: "post",
                    dataType: 'text',
                    contentType: "application/json; charset=utf-8",  //设置类型,注意一定不能丢  
                    success: function (data) {
                        console.log(data);
                    }
                }); 

原文地址:https://www.cnblogs.com/embaobao/p/10720843.html