【问题标题】:Can not call to Wcf Service from JavaScript无法从 JavaScript 调用 Wcf 服务
【发布时间】:2013-07-02 05:48:38
【问题描述】:

我有一个WCF 服务,我通过JS 调用Jquery 来使用它。

代码如下所示:

IService1.cs:

[ServiceContract]
public interface IService1
{
    [WebInvoke(Method = "POST",
    BodyStyle = WebMessageBodyStyle.Wrapped,
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    User GetUser(string userName, string password);
}

Service1.cs:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{   
    public User GetUser(string userName, string password)
    {
        //DO SOMETHING
    }
}

由 IIS 完成托管:

<%@ ServiceHost Language="C#" Debug="true" Service="MyProjectName.Service1" CodeBehind="Service1.svc.cs" %>

Web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
    <identity impersonate="false" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="EndpBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" 
                               multipleSiteBindingsEnabled="true" />
    <services>
      <service name="MyProjectName.Service1" 
               behaviorConfiguration="ServiceBehavior">
        <endpoint address="" 
                  behaviorConfiguration="EndpBehavior" 
                  binding="webHttpBinding" 
                  contract="MyProjectName.IService1" />
      </service>
    </services>
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint name="" />
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>
</configuration>

在我的 java 脚本页面中,我像这样调用 GetUser 函数:

function CallService() {
    jQuery.ajaxSetup({
        error: function (x, e) {
            if (x.status == 0) {
                alert('You are offline!!\n Please Check Your Network.');
            } else if (x.status == 404) {
                alert('Requested URL not found.');
            } else if (x.status == 500) {
                alert('Internal Server Error.');
            } else if (e == 'parsererror') {
                alert('Error.\nParsing JSON Request failed.');
            } else if (e == 'timeout') {
                alert('Request Time out.');
            } else {
                alert('Unknow Error.\n' + x.responseText);
            }
        }
    });
    var request = { userName: "aaa", password: "123" };
    var jsondata = JSON.stringify(request);

    $.ajax({
        type: "POST", //GET or POST or PUT or DELETE verb
        url: "http://localhost:xxxx/Service1.svc/GetUser", // Location of the service
        data: jsondata, //Data sent to server
        contentType: "application/json; charset=utf-8", // content type sent to server
        dataType: "json", //Expected data format from server
        processdata: true, //True or False
        crossDomain: true, //True or False
        success: function (result) {
           alert('success');
        }
    });
}

虽然我可以在浏览器中提升服务,但我不断收到错误:

你离线了!!请检查您的网络。

我找不到任何可以帮助我解决的问题,有人有想法吗?

【问题讨论】:

标签: javascript html wcf jquery


【解决方案1】:

我认为您的问题是您的 WS 不允许跨域访问。

您可以尝试将下一个代码添加到您的 Web.config

<configuration>
    <system.webServer>      
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
                <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
                <add name="Access-Control-Allow-Headers" value="Content-Type" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
    <!-- Rest of your code -->
</configuration>

【讨论】:

  • @HodayaShalom 您使用的是什么版本的 IIS?
  • @HodayaShalom 在这里你有一个他们解释它的链接forums.asp.net/t/1328833.aspx/1
  • @HodayaShalom 我在配置中添加了更多标题,尝试所有这些。似乎在 IIS 7.5 中您还需要 &lt;add name="Access-Control-Allow-Headers" value="*" /&gt; 这就是我询问您的版本的原因;)
  • @HodayaShalom 是的,我们在服务器中添加了支持以允许这样做,但我认为您现在的问题出在客户端。让我检查一下:)
  • @HodayaShalom 嘿 Hodaya,很高兴听到这个消息!很高兴你能解决它!
【解决方案2】:

不知道您是否尝试过,但使用 jsonp 进行跨站点脚本。
这是我在网上找到的一个例子。 XSS-WCF-From-JQuery

使用 JSONP 是一种绕过同源策略限制的技术。 JSONP 有其优点和缺点。花一些时间研究可能更好地满足您的项目需求的其他方法。

【讨论】:

  • 如果我把DataType改成dataType:"jsonp",我就不会进入成功函数,也不会进入错误函数。
  • @HodayaShalom - 好吧,事情没那么简单。您的服务器需要知道如何处理 jsonp 请求,并且需要知道如何构建正确的响应。这里 (blog.jonathanroussel.com/2010/01/…) 是一个可用于生成 jsonp 响应的 HttpModule 示例。 (在这个例子中,他使用 asmx WS,但我相信你会改变必要的)。
  • 仍然不明白为什么它不能使用 JSON。就像现在一样。
  • @HodayaShalom - 请阅读有关同源策略和 JSONP 的信息。这里 (en.wikipedia.org/wiki/JSONP) 是关于 JSONP 的维基百科解释以及相关主题的相关链接。通常,源自 www.server1.com 的网页无法通过脚本调用 www.server2.com。此规则有一些例外(如
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多