如何使用跨域的ajax调用asp.net Web服务

时间:2013-06-26 10:16:22

标签: javascript ajax web-services cors

我正在使用javascript,html,css(跨平台技术)开发移动应用程序,我使用asp .net编写了一个Web服务,我想从Web服务获取数据并使用javascript / jquery显示到客户端。我们指向Web服务并显示结果但这只能在IE(Internet Explorer)中工作,我们从服务器获得结果为“真实”响应,但在其他浏览器(Mozilla,chrome)中它不起作用,我们得到结果“ false“作为来自server.where的响应,因为我期待结果在所有浏览器中都显示为”true“,但它没有发生。我已经给出了我使用过的所有代码。

WebService.asmx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    [WebMethod]
    public bool GetValue(string id,string pwd)
    {
        string userid = "abc";
        string password = "xyz";
        if (userid==id && password==pwd)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}

Web.config

<?xml version="1.0"?>

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0"/>
    </system.web>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*"/>
                <add name="Access-Control-Allow-Headers" value="Content-Type"/>
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

HTML网页代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>
    </title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
   <script>
       function JsonTest2() {
jQuery.support.cors = true;
           $.ajax({
               type: 'POST',
               url: "http://10.16.10.35/webservice_test/WebService.asmx/GetValue",
               data: '{"id":"vipul","pwd":"borole"}',
               contentType: 'application/json; charset=UTF-8',
               dataType: 'json',
               async: false,
               success: function (msg) {
                   alert(msg.d);
               },
               error: function (msg) {
                   alert('failure');
                   alert(msg);
               }
           });
       }
   </script>
</head>
<body>
<input id="Button1" type="button" value="button" onclick="javascript:JsonTest2();" />

</body>
</html>

请帮我从所有浏览器调用此Web服务我无法理解为什么它返回false

1 个答案:

答案 0 :(得分:1)

您还需要具有POST的Access-Control-Allow-Methods。

另外,您意识到使用* for Origin允许任何人访问该服务?您可能希望使用适合实现CORS的库,例如Thinktecture IdentityModel库:

http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/

查看IIS / Url选项(因为它似乎是在IIS之外托管)。

相关问题