【问题标题】:Accessing Cross-Domain WCF-Webservice with jQuery or Javascript使用 jQuery 或 Javascript 访问跨域 WCF-Webservice
【发布时间】:2015-10-07 05:17:53
【问题描述】:

很抱歉再次问这个问题,但我没有找到适合我的问题的答案。

我尝试构建以下内容: 我想用标准网页连接到 WCF-Webservice。网站和网络服务都托管在同一台机器上的 IIS 中。

我为 web.config 启用了跨域:

<webHttpBinding>
    <binding name="webHttpBindingWithJSONP" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>

还有我的 AJAX 请求:

$.ajax({
    type: "POST",
    url: config.endpoints.db.production + "AddData/",
    data: JSON.stringify(data),
    contentType: "application/json",
    dataType: "json",
    crossDomain: true,
    //  processData: true,
    success: function(data, status, jqXHR) {
        //  alert("success..." + data);
        // loadingVisible(false);
        //  loadingFinished = true;


    },
    error: function(xhr) {
        alert("failure..." + xhr.responseText);
        //    loadingFinished = true;
        //    loadingVisible(false);

    }
});

发出请求后,我在 jquery 的 Visual Studio 中收到“访问被拒绝”-错误。 在网上搜索后发现这是一个很常见的跨域问题,但没有找到解决办法。我尝试在 ajax 请求中设置“crossDomain:true”,尝试使用 jsonp(它适用于我的 GET 请求)但没有任何帮助。

有没有合适的方法来解决这个问题?我读到这个问题可以通过 ajax 身份验证来解决。这是正确的,我怎样才能做到这一点?

【问题讨论】:

标签: javascript jquery ajax wcf cross-domain


【解决方案1】:

要解决问题,请执行以下操作

创建一个 Global.asax 并添加以下内容以启用 Ajax 跨域 POST

 public void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST,OPTIONS");

            if ((HttpContext.Current.Request.HttpMethod == "OPTIONS"))
            {

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }
    }

在您的服务中心

[AspNetCompatibilityRequirements(RequirementsMode =
    AspNetCompatibilityRequirementsMode.Allowed)]
    public class YourserviceName : YourserviceNameInterface

【讨论】:

    猜你喜欢
    • 2011-05-10
    • 2011-09-27
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2011-12-03
    • 2011-12-09
    • 2011-07-25
    相关资源
    最近更新 更多