2011-02-05 4 views
0

Я новичок в WCF. Я создал службу поддержки WCF в VS2010 (сервисное приложение WCF). Он был нацелен на Framework 4.0. Я размещал эту службу на локальном IIS с набором приложений для платформы 4.0. Когда я вызываю методы приложения из браузера или скрипача, они работают нормально. Теперь я создал клиентскую консоль. Когда я вызвать любой метод от клиента я получаю следующее сообщение Исключение:WCF Restful Client throwing «Удаленный сервер возвратил неожиданный ответ: (405) Метод не разрешен».

** Удаленный сервер возвратил неожиданный ответ: (405) Method Not Allowed **

Service Interface файла:.

namespace MyService 

{

[ServiceContract] 
public interface ITestService 
{ 


    [WebGet(UriTemplate = "GetDateTime")] 
    [OperationContract] 
    string GetDateTime(); 

    [WebGet(UriTemplate = "GetName")] 
    [OperationContract] 
    string GetName(); 

} 

}

класса, который реализует вышеупомянутый интерфейс:

namespace MyService 

{

public class TestService : ITestService 
    { 
     public string GetDateTime() 
     { 
      return DateTime.Now.ToString(); 
     } 

    public string GetName() 
    { 
     return "MY name is KingKong"; 
    } 
} 

}

Web.config файл:

<system.serviceModel> 
<services> 
    <service behaviorConfiguration="ServiceBehavior" name="MyService.TestService"> 
    <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" bindingConfiguration="" contract="MyService.ITestService"> 

    </endpoint> 
    </service> 
</services> 
<behaviors> 
    <endpointBehaviors> 
    <behavior name="web"> 
     <webHttp /> 
    </behavior> 
    </endpointBehaviors> 
    <serviceBehaviors> 
    <behavior name="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="false" /> 
    </behavior> 
    </serviceBehaviors> 
</behaviors> 
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 

TestService.svc

<% @ ServiceHost Язык = "C#" Debug = "истинный" Service = "MyService.TestService" CodeBehind = "TestService.svc.cs" %>

Клиент app.config:

<system.serviceModel> 
    <behaviors> 
     <endpointBehaviors> 
      <behavior name=""> 
       <webHttp /> 
      </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    <client> 
     <endpoint address="http://localhost/BestService/TestService.svc" 
      binding="webHttpBinding" bindingConfiguration="" contract="MyService.ITestService" 
      name="MyClientConfig" kind="" endpointConfiguration="" /> 
    </client> 
</system.serviceModel> 

Client Вызывающая программа прокси-класс

static void Main(string[] args) 
    { 
     TestServiceClient proxy = null; 
     try 
     { 
      proxy = new TestServiceClient(); 

      Console.WriteLine("Test 1: List all products"); 
      string sdatetime = proxy.GetName(); 

      Console.WriteLine("Datetime: {0}", sdatetime); 

      Console.WriteLine(); 

      // Disconnect from the service 
      proxy.Close(); 


     } 
     catch (CommunicationException cex) 
     { 

      if (cex.InnerException != null) 
      { 
       Console.WriteLine("{0}", cex.InnerException.Message); 
      } 
      else 
      { 
       Console.WriteLine("General exception: {0}", cex.Message); 
      } 
     } 
     catch (Exception e) 
     { 
      if (e.InnerException != null) 
      { 
       Console.WriteLine("{0}", e.InnerException.Message); 
      } 
      else 
      { 
       Console.WriteLine("General exception: {0}", e.Message); 
      } 
     } 

     Console.WriteLine("Press ENTER to finish"); 
     Console.ReadLine(); 
    } 

Я добавил ссылку на службу в приложение и файл Reference.cs имеет следующий частичный код:

имен MyClient.MyService {

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] 
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="MyService.ITestService")] 
public interface ITestService { 

    [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ITestService/GetDateTime", ReplyAction="http://tempuri.org/ITestService/GetDateTimeResponse")] 
    string GetDateTime(); 

    [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ITestService/GetName", ReplyAction="http://tempuri.org/ITestService/GetNameResponse")] 
    string GetName(); 
} 

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] 
public interface ITestServiceChannel : MyClient.MyService.ITestService, System.ServiceModel.IClientChannel { 
} 

[System.Diagnostics.DebuggerStepThroughAttribute()] 
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] 
public partial class TestServiceClient : System.ServiceModel.ClientBase<MyClient.MyService.ITestService>, MyClient.MyService.ITestService { 

    public TestServiceClient() { 
    } 

    public TestServiceClient(string endpointConfigurationName) : 
      base(endpointConfigurationName) { 
    } 

    public TestServiceClient(string endpointConfigurationName, string remoteAddress) : 
      base(endpointConfigurationName, remoteAddress) { 
    } 

    public TestServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
      base(endpointConfigurationName, remoteAddress) { 
    } 

    public TestServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
      base(binding, remoteAddress) { 
    } 

    public string GetDateTime() { 
     return base.Channel.GetDateTime(); 
    } 

    public string GetName() { 
     return base.Channel.GetName(); 
    } 
} 

}

Пожалуйста, помогите мне, поскольку я провел около у 2 дня, пытаясь выяснить проблему в клиенте

Благодаря

+0

Это просто ** слишком много вещей! ** Можете ли вы сузить его до простого сервиса, одного единственного метода и отладить его? .... –

+0

FYI: http: //localhost/BestService/TestService.svc/ <== BestService - это имя каталога virtaul в IIS, указывающего на папку приложения службы WCF, где находится файл TestService.svc. – user604463

+0

Любой вход ..puleze :( – user604463

ответ

0

VS2010 оленья кожа имеет способность генерировать прокси для RESTful службы, как это делает для службы на основе SOAP.Таким образом, решение представляет собой собственный класс прокси, который наследуется от класса ClientBase и использует канал для вызова веб-методов службы.