2013-08-21 5 views
0

У меня есть служба WCF с тремя конечными точками с различными привязками (basicHttpBinding для мыльных клиентов, webHttpBinding для jQuery ajax client и mex).Использовать JQuery AJAX для вызова службы WCF с несколькими привязками

я могу получить доступ к службе через SOAP (путем добавления ссылки на службу в то время):

 ServiceRef.IService service = new ServiceClient("BasicHttpBinding_IService"); 
     Response.Write(service.TestMethod("hi")); 

Но почему я называю из JQuery Ajax Я получаю 404 ошибку.

Если я копирую службу в тестовый проект и определяю только один webHttpBinding, я могу позвонить службе через jquery.

IService.cs

[ServiceContract] 
    public interface IService 
    { 
     [OperationContract] 
     [WebInvoke(Method = "POST", 
     ResponseFormat = WebMessageFormat.Json)] 
     Response TestMethod(string Id); 
.... 

Service.cs

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
[ServiceBehavior] 
public class Service : IService 
{ 
    [OperationBehavior] 
    public Response TestMethod(string Id) 
    { 
     Response resp = new Response(); 
     resp.Message = "hello"; 
     return resp; 
    } 
.... 

Web.Config

<system.serviceModel> 
    <serviceHostingEnvironment multipleSiteBindingsEnabled="false" aspNetCompatibilityEnabled="true" /> 
<services> 
    <service 
    name="eBooks.Presentation.Wcf.Service" 
    behaviorConfiguration="eBooks.Presentation.Wcf.ServiceBehavior"> 
    <!-- use base address provided by host --> 
    <!-- specify BasicHttp binding and a binding configuration to use --> 
    <endpoint address="soap" 
       binding="basicHttpBinding" 
       bindingConfiguration="Binding1" 
       contract="eBooks.Presentation.Wcf.IService" /> 
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> 
     <endpoint address="" binding="webHttpBinding" 
      contract="eBooks.Presentation.Wcf.IService" behaviorConfiguration="EndpBehavior"/> 
    </service> 
</services> 
<bindings> 
    <!-- 
     Following is the expanded configuration section for a BasicHttpBinding. 
     Each property is configured with the default value. 
     See the TransportSecurity, and MessageSecurity samples in the 
     Basic directory to learn how to configure these features. 
     --> 
    <basicHttpBinding> 
    <binding name="Binding1" 
      hostNameComparisonMode="StrongWildcard" 
      receiveTimeout="00:10:00" 
      sendTimeout="00:10:00" 
      openTimeout="00:10:00" 
      closeTimeout="00:10:00" 
      maxReceivedMessageSize="65536" 
      maxBufferSize="65536" 
      maxBufferPoolSize="524288" 
      transferMode="Buffered" 
      messageEncoding="Text" 
      textEncoding="utf-8" 
      bypassProxyOnLocal="false" 
      useDefaultWebProxy="true" > 
     <security mode="None" /> 
    </binding> 
    </basicHttpBinding> 
</bindings> 
<behaviors> 
    <serviceBehaviors> 
    <behavior name="eBooks.Presentation.Wcf.ServiceBehavior"> 
     <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> 
     <serviceMetadata httpGetEnabled="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="true"/> 
    </behavior> 
    </serviceBehaviors> 
    <endpointBehaviors> 
    <behavior name="EndpBehavior"> 
     <webHttp/> 
    </behavior> 
    </endpointBehaviors> 
</behaviors> 

Jquery

function CallService() { 
     $.ajax({ 
      type: "POST", //GET or POST or PUT or DELETE verb 
      url: "http://localhost:888/Service.svc/TestMethod", // Location of the service 
      data: '{"Id": "1"}', //Data sent to server 
      contentType: "application/json; charset=utf-8", // content type sent to server 
      dataType: "json", //Expected data format from server 
      processdata: ProcessData, //True or False 
      success: function (msg) {//On Successfull service call 
       ServiceSucceeded(msg); 
      }, 
      error: ServiceFailed// When Service call fails 
     }); 
    } 

В моей конфигурации конечной точки я установить адрес для webHttp конечной точки, чтобы быть «» как я не знаю, как выбрать конкретную конечную точку при вызове из JQuery.

У кого-нибудь есть идеи, почему я получаю эту ошибку 404?

ответ

0

1) Убедитесь, что ваш Service.svc находится в корневом каталоге.

2) Добавить

[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)] 

К месту, где вы создать экземпляр TestMethod. например:

[OperationBehavior] 
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)] 
public Response TestMethod(string Id) 
{ 
    Response resp = new Response(); 
    resp.Message = "hello"; 
    return resp; 
} 

Любой из них поможет?

+0

Да, [WebInvoke], вероятно, не нужен. Но стоит попробовать. – Richard

Смежные вопросы