0

我正在开发两个网站。在其中一个我有页面Service.aspx,有一些WebMethod。我想从其他站点访问它们。

Service.aspx

namespace Interface
{   
    public partial class Service : System.Web.UI.Page
    {
        [WebMethod]
        public static bool CheckUserLogin(string login)
        {
            BL.UserBL logic = new BL.UserBL();                
            return logic.isUnique(login);
        }
    }
}

script.js

function isGoodLogin() {
    var login = $("[id$='tbSignUpLogin']").val();
    var data = '{"login":"' + login + '"}';
    var flag = false;
    $.ajax({
        type: "POST",
        url: "http://95.31.32.69/Service.aspx/CheckUserLogin",
        async: false,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (msg.d == true) {
                flag = true;
            }
        },
        error: function (xhr, status, error) {
            handleException(xhr.responseText)
        }
    });
    return flag;
}

之后,当我使用脚本时,出现错误:

XmlHttpRequest 错误:Access-Control-Allow-Origin 不允许 Origin null

然后我尝试解决这个问题。我的Web.config

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </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>
  <connectionStrings>
    <add name="TestSystemEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=WIN-V5EHKO65FPU\SQLEXPRESS;Initial Catalog=C:\INETPUB\ACMTESTSYSTEM\INTERFACE\APP_DATA\TESTSYSTEM.MDF;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

之后我尝试使用Global.asax

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
}

然后我尝试使用WebService.asmx

namespace Interface
{
   [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    {

        [WebMethod]
        public bool CheckUserLogin(string login)
        {
            BL.UserBL logic = new BL.UserBL();
            return logic.isUnique(login);
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public string Foo()
        {
            var json = new JavaScriptSerializer().Serialize(new
            {
                Prop1 = "some property",
            });
            string jsoncallback = HttpContext.Current.Request["jsoncallback"];
            return string.Format("{0}({1})", jsoncallback, json);
        }
    }
}

也许我的脚本有问题?

1:

var dataURL = "http://95.31.32.69/WebService.asmx/CheckUserLogin?login=1";
$.getJSON(dataURL+"&jsoncallback=?",myCallback);
function myCallback(data){     
 alert(data);
}

返回错误:

未捕获的 SyntaxError:意外的令牌 <

2:

function isGoodLogin2() {
    var login = $("[id$='tbSignUpLogin']").val();
    var data = '{"login":"' + login + '"}';
    var flag = false;
    $.ajax({
        type: "POST",
        url: "http://95.31.32.69/WebService.asmx/CheckUserLogin",
        async: false,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
                success: function (msg) {
            if (msg.d == true) {
                flag = true;
            }
        },
        error: function (xhr, status, error) {
            handleException(xhr.responseText)
        }
    });
    return flag;
}

返回错误:

XMLHttpRequest 无法加载http://95.31.32.69/WebService.asmx/CheckUserLogin。Access-Control-Allow-Origin 不允许 Origin null。

3:

  var url = 'http://95.31.32.69/WebService.asmx/CheckUserLogin?login=1&callback=?';
  $.get(url, function (data) {
    alert(data);
  });

返回错误:

XMLHttpRequest 无法加载http://95.31.32.69/WebService.asmx/CheckUserLogin。Access-Control-Allow-Origin 不允许 Origin null。

4:

var dataURL = "http://95.31.32.69/WebService.asmx/Foo";
    $.getJSON(dataURL+"&jsoncallback=?",myCallback);
    function myCallback(data){     
     alert(data);
    }

返回错误:

加载资源失败:服务器响应状态为 400(错误请求)

还有许多其他人。该网站在 IIS 7 上运行。

4

1 回答 1

1

由于安全原因,AJAX调用只能在同一个源服务器上进行,即Same-Origin-Policy 。对于跨域请求,使用 JSONP 等其他方法。因此错误Origin null is not allowed by Access-Control-Allow-Origin.

同源政策

于 2013-05-02T13:28:45.750 回答