简体   繁体   English

跨站点Ajax WebService或WebMethod

[英]Cross-site Ajax WebService or WebMethod

I am developing two sites. 我正在开发两个站点。 In one of them I have page Service.aspx , that have some WebMethod . 在其中之一中,我有Service.aspx页面,其中有一些WebMethod I want to have access to them from other site. 我想从其他站点访问它们。

Service.aspx : 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 : 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;
}

After that, when I use my script, I have error: 之后,当我使用脚本时,出现错误:

XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin XmlHttpRequest错误:Access-Control-Allow-Origin不允许使用原点null

Then I try to solve this problem. 然后我尝试解决这个问题。 My Web.config : 我的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>

After that I try to use Global.asax : 之后,我尝试使用Global.asax

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

Then I try to use WebService.asmx : 然后,我尝试使用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);
        }
    }
}

Maybe problem in my scripts? 也许我的脚本有问题?

1: 1:

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

Returns the error: 返回错误:

Uncaught SyntaxError: Unexpected token < 未捕获到的SyntaxError:意外令牌<

2: 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;
}

Returns the error: 返回错误:

XMLHttpRequest cannot load http://95.31.32.69/WebService.asmx/CheckUserLogin . XMLHttpRequest无法加载http://95.31.32.69/WebService.asmx/CheckUserLogin Origin null is not allowed by Access-Control-Allow-Origin. Access-Control-Allow-Origin不允许使用Origin null。

3: 3:

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

Returns the error: 返回错误:

XMLHttpRequest cannot load http://95.31.32.69/WebService.asmx/CheckUserLogin . XMLHttpRequest无法加载http://95.31.32.69/WebService.asmx/CheckUserLogin Origin null is not allowed by Access-Control-Allow-Origin. Access-Control-Allow-Origin不允许使用Origin null。

4: 4:

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

Returns the error: 返回错误:

Failed to load resource: the server responded with a status of 400 (Bad Request) 加载资源失败:服务器响应状态为400(错误请求)

And many others. 还有许多其他。 The web site works on IIS 7. 该网站可在IIS 7上运行。

AJAX calls can only be made on the same originating server ie Same-Origin-Policy due to security reasons. 由于安全原因, AJAX调用只能在同一原始服务器上进行,即Same-Origin-Policy Use other methods such as JSONP for cross-domain requests. 对跨域请求使用其他方法,例如JSONP。 Hence the error Origin null is not allowed by Access-Control-Allow-Origin. 因此Origin null is not allowed by Access-Control-Allow-Origin.出现错误Origin null is not allowed by Access-Control-Allow-Origin.

Same-Origin Policy 原产地政策

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM