WCF REST服务返回方法未找到

时间:2014-04-23 03:38:51

标签: c# asp.net json wcf rest

我开发了一个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”,它会抛出“传输错误”

我该怎么办?

更新 service 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>

1 个答案:

答案 0 :(得分:3)

编辑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 practiceREST API design

  5. 了解详情
  6. 方法实现示例:

    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;
    }
    
  7. 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)

  8. 仅用于调试目的,包括对故障消息的异常堆栈跟踪。更改服务项目上的web.config(includeExceptionDetailInFaults =“true”):

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