找不到WCF REST服务返回方法

本文关键字:返回 方法 服务 REST WCF 找不到 | 更新日期: 2023-09-27 17:59:23

我开发了一个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",它将抛出"transport error"

我该怎么办?

更新:服务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>

找不到WCF REST服务返回方法

编辑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最佳实践,REST API设计

  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>