【问题标题】:WCF REST Service return Method not found未找到 WCF REST 服务返回方法
【发布时间】:2014-04-23 03:38:50
【问题描述】:

我已经开发了一个 WCF REST 服务并尝试使用 Asp.net 进行测试,尽管它可以与 wcf 测试客户端一起使用。该服务可能被非点网客户端使用。

我正在尝试在 asp.net 中创建一个测试页面,以通过 post 验证此服务。目前,此服务托管在我的 IIS 中

服役中:

[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/MySVC?stringP={stringP}")]
        Stream MySVC(string stringP); 

在 asp.net 中

$.ajax({
            type: "POST", //GET or POST or PUT or DELETE verb
            url: "http://localhost/MySvcHost/MySVC.svc?stringP",
            cache: false,
            data: '[{stringP:"samplestring"}]',
            dataType: "jsonp",
            processData: true,
            success: function (msg) {
            },
            error: function (err) {
            }
        })

当我运行测试应用程序时,它进入错误块 & Fiddler 显示错误“方法不允许”并显示为 GET。我还看到了附加参数(callback=)如果我将“jsonp”更改为“json”,它会抛出“传输错误”

我该怎么办?

更新: 服务 web.config

  <system.serviceModel>
    <services>
      <service
        name="Service.ParseService" behaviorConfiguration="ServiceBehaviour" >
        <endpoint address="" binding="webHttpBinding" behaviorConfiguration="web"
                  contract="Service.RestServiceInterface" name="BasicHttpBinding_RestServiceInterface2">
        </endpoint>
      </service>
    </services>   
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp defaultOutgoingResponseFormat="Json" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding maxBufferPoolSize="2000000" maxReceivedMessageSize="2000000" useDefaultWebProxy="true" allowCookies="false" name="crossDomain" crossDomainScriptAccessEnabled="true" hostNameComparisonMode="StrongWildcard" receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00"
                   maxBufferSize="2147483647" transferMode="Buffered"
                   bypassProxyOnLocal="false">
              <readerQuotas maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="1024" maxStringContentLength="2147483647" maxNameTableCharCount="16384"></readerQuotas>

        </binding>
      </webHttpBinding>
    </bindings>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

客户端 web.config

<system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webEndpoint">
          <webHttp defaultBodyStyle="Wrapped" defaultOutgoingResponseFormat="Json"
              helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding  name="BasicHttpBinding_RestServiceInterface2" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
          allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
          maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
          transferMode="Buffered"
          useDefaultWebProxy="true">
          <readerQuotas maxDepth="1024" maxStringContentLength="2147483647" maxArrayLength="2147483647"
            maxBytesPerRead="2147483647" maxNameTableCharCount="16384" />
        </binding>
      </webHttpBinding>
    </bindings>
    <client>
      <endpoint behaviorConfiguration="webEndpoint" address="http://localhost:14502/MySvcHost/MySVC.svc" binding="webHttpBinding" bindingConfiguration="BasicHttpBinding_RestServiceInterface2" contract="MySVC.RestServiceInterface" name="BasicHttpBinding_RestServiceInterface2"/>
    </client>

【问题讨论】:

  • 我怀疑是 Stream 返回类型,你能用字符串等其他返回类型来测试它吗?
  • 我怀疑,它与 Stream 类型无关。我更改为字符串并在应用程序中遇到相同的错误。事实上,我尝试通过托管链接访问..

标签: c# asp.net json wcf rest


【解决方案1】:

编辑 3:

  1. 将 baseAddress 添加到您的 web.config 并删除所有不必要的内容:

    <system.serviceModel>
      <services>
        <service name="Service.ParseService"
                 behaviorConfiguration="ServiceBehaviour" >
          <endpoint address="" 
                    binding="webHttpBinding" behaviorConfiguration="webBehavior"
                    contract="Service.RestServiceInterface" name="BasicHttpBinding_RestServiceInterface2">
          </endpoint>
          <host>
            <baseAddresses>
              <add baseAddress="http://localhost:14502/MySvcHost/MySVC.svc"/>
            </baseAddresses>
          </host>
        </service>
      </services>
      <behaviors>
        <serviceBehaviors>
          <behavior name="ServiceBehaviour">
            <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
            <serviceDebug includeExceptionDetailInFaults="false"/>
          </behavior>
        </serviceBehaviors>
        <endpointBehaviors>
          <behavior name="webBehavior">
            <webHttp />
          </behavior>
        </endpointBehaviors>
      </behaviors>
    
    </system.serviceModel>
    
  2. 启用 CORS,在服务项目的 web.config 中添加这样的行:

    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Methods" value="GET, POST" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>
    
  3. 您的项目中必须有 MySVC.svc。内容应该是这样的:

    <%@ ServiceHost Language="C#" Factory="System.Data.Services.DataServiceHostFactory, System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Service="Service.ParseService" %>
    
  4. 界面应该是:

    [ServiceContract]
    public interface RestServiceInterface
    {
       [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "MySVC")]
       Stream MySVC(string stringP); 
    
    }
    

    *注意接口名应该从 I 开始 - IFileService, IMessageService...
    *Uri 应该标识资源并且应该像这样描述:

    POST: http://localhost/files/
    GET: http://localhost/files/1
    

    在REST API best practice、REST API design了解更多信息

  5. 方法实现示例:

    public Stream MySVC(string stringP)
    {
        var mem = new MemoryStream();
        var ser = new DataContractJsonSerializer(typeof(string));
        ser.WriteObject(mem, stringP);
    
        mem.Seek(0, SeekOrigin.Begin);
    
        return mem;
    }
    
  6. Ajax 调用:

    $.ajax(
    {
        type: "POST",
        processData: false,
        contentType: "application/json",
        url: "http://localhost:14502/MySvcHost/MySVC.svc/MySVC",
        data: '"plnainString"',
        dataType: "jsonp",
        success: function (data) { alert(data); },
        error: function (data) { alert('error')); }
    })
    

    *注意:如果您从不同的机器调用服务然后托管服务,您必须将 localhost 更改为具体的机器名称(或 IP)

  7. 仅用于调试目的启用包括异常堆栈跟踪到故障消息。更改服务项目的 web.config (includeExceptionDetailInFaults="true"):

    <serviceBehaviors>
      <behavior name="ServiceBehaviour">
        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="true"/>
      </behavior>
    </serviceBehaviors>
    

【讨论】:

  • 谢谢。我根据您的建议更改了 UriTemplate 但没有奏效。我仍然在 ajax 上看到“无传输”错误。我还在 asp.net 应用程序中添加了 ServiceReference 进行测试。我得到不同的错误“localhost/MySvcHost/MySVC.svc没有端点监听
  • 错误是“远程服务器返回了一个意外的响应(400)错误请求。”虽然我可以通过 URL 访问服务。如何通过邮寄方式发送数据?
  • 因为您可以从 url 而不是从 application 访问它,可能是 CORS 问题。
  • @user1480864 同意,似乎是 CORS 问题。请参阅更新:编辑 1。您能否还建议它是否适用于提琴手?
  • @Legart 我在服务 web.config 中添加了您建议的行。我仍然从服务参考中看到相同的错误和 ajax 中的“无传输”错误。我可以在浏览器中点击服务 url,但不确定如何测试 POST 功能。没有想法了!
猜你喜欢
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
  • 2017-10-13
  • 2011-12-27
  • 1970-01-01
  • 2015-04-26
相关资源
最近更新 更多