Punkty końcowe REST / SOAP dla usługi WCF

Mam usługę WCF i chcę ją ujawnić zarówno jako usługę RESTfull, jak i jako usługę SOAP. Ktoś już coś takiego robił?

 409
Author: John Saunders, 2008-10-09

6 answers

Możesz wyświetlić usługę w dwóch różnych punktach końcowych. SOAP można użyć wiązania wspierającego SOAP np. basicHttpBinding, RESTful można użyć webHttpBinding. Zakładam, że usługa REST będzie w JSON, w takim przypadku musisz skonfigurować dwa punkty końcowe z następującą konfiguracją zachowania

<endpointBehaviors>
  <behavior name="jsonBehavior">
    <enableWebScript/>
  </behavior>
</endpointBehaviors>

Przykład konfiguracji punktu końcowego w Twoim scenariuszu to

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="ITestService"/>
  </service>
</services>

Więc usługa będzie dostępna at

Zastosuj [WebGet] do umowy operacyjnej, aby była pełna. np.

public interface ITestService
{
   [OperationContract]
   [WebGet]
   string HelloWorld(string text)
}

Uwaga, Jeśli usługa REST nie jest w JSON, parametry operacji nie mogą zawierać typu złożonego.

Reply to the post for SOAP and RESTful POX (XML)

Dla zwykłego starego XML jako formatu zwracanego, jest to przykład, który będzie działał zarówno dla SOAP, jak i XML.

[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
    [OperationContract]
    [WebGet(UriTemplate = "accounts/{id}")]
    Account[] GetAccount(string id);
}

POX zachowanie dla odpoczynku zwykły stary XML

<behavior name="poxBehavior">
  <webHttp/>
</behavior>

Punkty końcowe

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="xml" binding="webHttpBinding"  behaviorConfiguration="poxBehavior" contract="ITestService"/>
  </service>
</services>

Usługa będzie dostępna pod adresem

Prośba o odpoczynek spróbuj w przeglądarce,

Http://www.example.com/xml/accounts/A123

Soap request konfiguracja punktu końcowego klienta dla usługi SOAP po dodanie referencji serwisowej,

  <client>
    <endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
      contract="ITestService" name="BasicHttpBinding_ITestService" />
  </client>

W C #

TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");

Innym sposobem jest ujawnienie dwóch różnych umów serwisowych i każdy z określoną konfiguracją. Może to generować pewne duplikaty na poziomie kodu, jednak na koniec dnia chcesz, aby działał.

 569
Author: codemeit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-04 02:12:29

Ten post ma już bardzo dobrą odpowiedź "Community wiki" i polecam również zajrzeć na Blog Ricka Strahla, jest wiele dobrych postów o WCF Rest jak to .

Użyłem obu, aby uzyskać ten rodzaj MyService-service... Następnie mogę użyć REST-interface z jQuery lub SOAP z Javy.

To jest z mojej strony.Config:
<system.serviceModel>
 <services>
  <service name="MyService" behaviorConfiguration="MyServiceBehavior">
   <endpoint name="rest" address="" binding="webHttpBinding" contract="MyService" behaviorConfiguration="restBehavior"/>
   <endpoint name="mex" address="mex" binding="mexHttpBinding" contract="MyService"/>
   <endpoint name="soap" address="soap" binding="basicHttpBinding" contract="MyService"/>
  </service>
 </services>
 <behaviors>
  <serviceBehaviors>
   <behavior name="MyServiceBehavior">
    <serviceMetadata httpGetEnabled="true"/>
    <serviceDebug includeExceptionDetailInFaults="true" />
   </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
   <behavior name="restBehavior">
    <webHttp/>
   </behavior>
  </endpointBehaviors>
 </behaviors>
</system.serviceModel>

A to jest moja klasa służby (.svc-codebehind, brak wymaganych interfejsów):

    /// <summary> MyService documentation here ;) </summary>
[ServiceContract(Name = "MyService", Namespace = "http://myservice/", SessionMode = SessionMode.NotAllowed)]
//[ServiceKnownType(typeof (IList<MyDataContractTypes>))]
[ServiceBehavior(Name = "MyService", Namespace = "http://myservice/")]
public class MyService
{
    [OperationContract(Name = "MyResource1")]
    [WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "MyXmlResource/{key}")]
    public string MyResource1(string key)
    {
        return "Test: " + key;
    }

    [OperationContract(Name = "MyResource2")]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "MyJsonResource/{key}")]
    public string MyResource2(string key)
    {
        return "Test: " + key;
    }
}

Faktycznie używam tylko Json lub Xml ale oba są tutaj w celu demonstracji. To są prośby o pobranie danych. Aby wstawić dane użyłbym metody z atrybutami:

[OperationContract(Name = "MyResourceSave")]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "MyJsonResource")]
public string MyResourceSave(string thing){
    //...
 35
Author: Tuomas Hietanen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-19 11:28:51

Jeśli chcesz stworzyć tylko jedną usługę internetową i mieć ją hostowaną na wielu różnych punktach końcowych (np. SOAP + REST, z wyjściami XML, JSON, CSV, HTML). Należy również rozważyć użycie ServiceStack które zbudowałem dokładnie w tym celu, gdzie każda usługa, którą rozwijasz, jest automatycznie dostępna zarówno na soap, jak i REST po wyjęciu z pudełka, bez żadnej konfiguracji.

Przykład Hello World pokazuje jak stworzyć prosty z usługą with just (no Config required):

public class Hello {
    public string Name { get; set; }
}

public class HelloResponse {
    public string Result { get; set; }
}

public class HelloService : IService
{
    public object Any(Hello request)
    {
        return new HelloResponse { Result = "Hello, " + request.Name };
    }
}

Nie jest wymagana żadna inna konfiguracja, a ta usługa jest natychmiast dostępna z REST in:

Jest również wbudowany w przyjazne wyjście HTML (gdy jest wywoływane z klientem HTTP, który ma Accept:text/html np. przeglądarkę), dzięki czemu możesz lepiej wizualizować wyjście swoich usług.

Obsługa różne czasowniki REST są równie trywialne, oto kompletna aplikacja REST-service CRUD na 1 stronie C# (mniej niż potrzeba, aby skonfigurować WCF;): {]}

 24
Author: mythz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-08 12:43:27

MSDN wydaje się mieć artykuł na ten temat:

Https://msdn.microsoft.com/en-us/library/bb412196 (v=vs.110). aspx

Intro:

Domyślnie Windows Communication Foundation (WCF) udostępnia punkty końcowe tylko klientom SOAP. W jak: utworzyć podstawową usługę WCF Web HTTP, punkt końcowy jest dostępny dla klientów innych niż SOAP. Może się zdarzyć, że ta sama umowa będzie dostępna w obie strony, jako punkt końcowy sieci Web i jako punkt końcowy SOAP. Ten temat pokazuje przykład, jak to zrobić.

 6
Author: FMFF,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-02 00:39:32

Musimy zdefiniować konfigurację zachowania na REST endpoint

<endpointBehaviors>
  <behavior name="restfulBehavior">
   <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
  </behavior>
</endpointBehaviors>

A także do serwisu

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

Po zachowaniach, następnym krokiem są wiązania. Na przykład basicHttpBinding do soap endpoint i webHttpBinding do REST.

<bindings>
   <basicHttpBinding>
     <binding name="soapService" />
   </basicHttpBinding>
   <webHttpBinding>
     <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
   </webHttpBinding>
</bindings>

Na koniec musimy zdefiniować 2 punkty końcowe w definicji usługi. Uwaga na adres = "" punktu końcowego, gdzie do odpoczynku usługi nie jest konieczne nic.

<services>
  <service name="ComposerWcf.ComposerService">
    <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
    <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
    <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
  </service>
</services>

W interfejsie usługa definiujemy operację za pomocą jej atrybutów.

namespace ComposerWcf.Interface
{
    [ServiceContract]
    public interface IComposerService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/autenticationInfo/{app_id}/{access_token}", ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        Task<UserCacheComplexType_RootObject> autenticationInfo(string app_id, string access_token);
    }
}
/ Align = "center" bgcolor = "# e0ffe0 " / cesarz chin / / align = center / serviceModel definition.
<system.serviceModel>

  <behaviors>
    <endpointBehaviors>
      <behavior name="restfulBehavior">
        <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
      </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
    </serviceBehaviors>
  </behaviors>

  <bindings>
    <basicHttpBinding>
      <binding name="soapService" />
    </basicHttpBinding>
    <webHttpBinding>
      <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
    </webHttpBinding>
  </bindings>

  <protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
  </protocolMapping>

  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

  <services>
    <service name="ComposerWcf.ComposerService">
      <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
      <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
      <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
    </service>
  </services>

</system.serviceModel>

Aby przetestować oba punkty końcowe, możemy użyć WCFClientdo SOAPi PostMando REST.

 0
Author: Jailson Evora,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-05 01:20:31

To jest to, co zrobiłem, aby to zadziałało. Upewnij się, że put
webHttp automaticFormatSelectionEnabled="true" wewnątrz zachowania punktu końcowego.

[ServiceContract]
public interface ITestService
{

    [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/product", ResponseFormat = WebMessageFormat.Json)]
    string GetData();
}

public class TestService : ITestService
{
    public string GetJsonData()
    {
        return "I am good...";
    }
}

Wewnątrz modelu usługi

   <service name="TechCity.Business.TestService">

    <endpoint address="soap" binding="basicHttpBinding" name="SoapTest"
      bindingName="BasicSoap" contract="TechCity.Interfaces.ITestService" />
    <endpoint address="mex"
              contract="IMetadataExchange" binding="mexHttpBinding"/>
    <endpoint behaviorConfiguration="jsonBehavior" binding="webHttpBinding"
              name="Http" contract="TechCity.Interfaces.ITestService" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8739/test" />
      </baseAddresses>
    </host>
  </service>

Zachowanie Punktu Końcowego

  <endpointBehaviors>
    <behavior name="jsonBehavior">
      <webHttp automaticFormatSelectionEnabled="true"  />
      <!-- use JSON serialization -->
    </behavior>
  </endpointBehaviors>
 0
Author: Nayas Subramanian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 09:06:47