【问题标题】:what's wrong with this wcf rest implementation?这个 wcf rest 实现有什么问题?
【发布时间】:2016-10-12 23:55:59
【问题描述】:

我有一个 wcf 休息服务方法。 OperationContract 如下所示:

[OperationContract]
[WebGet(UriTemplate = "?maps/reporttypes/{reportType}/reportperiods/{reportPeriod}", ResponseFormat=WebMessageFormat.Json)]
Map GetData(int reportType, int reportPeriod);

我可以使用 WCF 测试客户端成功测试这个,所以我知道底层方法有效。但是,我在使用 $.ajax() 方法获取数据时遇到问题:

$.ajax({    
    url: 'http://localhost:52672/Service1.svc?maps/reporttypes/1/reportperiods/1',
    success:function(data){
       //bind data here
    },
    error:function(error){
    }
});

上面的 ajax 方法返回成功,但如果您为服务选择“在浏览器中查看”,则数据值只是显示的页面的 html。知道我在这个实现中可能缺少什么吗?

【问题讨论】:

  • 我认为网址中有错字。应该用斜杠代替问号:localhost:8080/service1.svc/reports/reportypes...
  • 另外,请注意 UriTemplate 中还有一个错字。一个段是 reporttypes 而不是 reporttypes。但是由于它在两个地方都拼错了,所以应该没有太大关系;)
  • 我更新了开发环境中的代码以及原始帖子中的代码。 url 返回成功,但仅返回默认服务视图的 html。我在这里错过了什么?
  • 两者都在同一个端口上运行吗?如果提到了一些错误,你能看到 html 吗?
  • 它们在不同的端口上运行。主网站在 localhost:8080 上运行,而服务在 localhost:52672 上运行。 html中没有错误。 html 只是反映了服务的通用 html 页面:jsbin.com/juwizokoje/edit?html,output

标签: c# .net ajax rest wcf


【解决方案1】:

正如您已经发现的那样,您的配置存在根本问题。 为了使用安静的 WCF 服务,您需要 webHttpBinding 而不是您正在使用的 basicHttpBinding

一个工作配置的例子是<system.serviceModel>-node:

<system.serviceModel>
  <services>
    <service behaviorConfiguration="Default" name="MapService5.Service1">
      <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="MapService5.IService1" />
    </service>
  </services>
  <behaviors>
    <endpointBehaviors>
      <behavior name="webBehavior">
        <webHttp />
      </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
      <behavior name="Default">
        <serviceMetadata httpGetEnabled="true"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>

完成该更改后,您已经可以直接通过浏览器调用该方法:

下一个错误原因是已经提到的问号,您使用不正确。您尝试像这样调用该方法:

http://localhost:52672/Service1.svc?maps/reporttypes/1/reportperiods/1

而它必须像这样被调用:

http://localhost:52672/Service1.svc/maps/reporttypes/1/reportperiods/1

请注意Service1.svc 后面的斜线 (/)。

如果您使用问号 (?),则字符串的其余部分 (?maps/reporttypes/1/reportperiods/1) 将被视为 查询字符串,这不是您要查找的内容在你的情况下。您需要一个没有任何查询参数的简单GET,这可以通过使用上面的后一个链接来实现。

UriTemplate 必须恢复为之前的字符串。再次问号与斜线问题;)

[WebGet(UriTemplate = "/maps/reporttypes/{reportType}/reportperiods/{reportPeriod}", ResponseFormat=WebMessageFormat.Json)]

【讨论】:

    猜你喜欢
    • 2012-05-26
    • 2021-10-17
    • 2011-09-28
    • 2011-12-14
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多