How to create a WCF (.NET) POST type method that receives a String parameter from the URL and Stream via POST?

Asked

Viewed 213 times

0

I tried to use in my service but I can’t get anything other than this error.

Error:

ExceptionDetail, provavelmente criado por IncludeExceptionDetailInFaults=true, cujo valor é:
    System.InvalidOperationException: Foi gerada uma exceção em uma chamada a uma extensão de exportação WSDL: System.ServiceModel.Description.DataContractSerializerOperationBehavior
     contrato: http://tempuri.org/:IHemoPlusApp ----> System.InvalidOperationException: Para a solicitação na operação SalvarPdf ser um fluxo, a operação deve ter um parâmetro único cujo tipo é Stream.

web config.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>
  <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="endp.WebHttp" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" transferMode="Streamed" sendTimeout="00:05:00">
          <readerQuotas  maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
          <security mode="None" />
        </binding>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="servicebehaviors">
          <!-- Para evitar a divulgação de informações de metadados, defina os valores abaixo para falso antes da implantação -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- Para receber detalhes de exceção em falhas para fins de depuração, defina o valor abaixo para verdadeiro. Defina para falto antes da implantação para evitar a divulgação de informações de exceção -->
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="servicebehaviors" name="HemoPlusApp.Service.HemoPlusApp">
        <endpoint bindingConfiguration="endp.WebHttp" address="" behaviorConfiguration="web" binding="webHttpBinding" contract="HemoPlusApp.Service.IHemoPlusApp" />
      </service>
    </services>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <!--
        Para procurar o diretório de raiz do aplicativo Web durante a depuração, defina o valor abaixo para verdadeiro.
        Defina-o para falso antes da implantação para evitar a divulgação de informações da pasta do aplicativo Web.
-->
    <directoryBrowse enabled="true" />
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
  <connectionStrings>
    <!--<add name="DataContext" connectionString="data source=LUCAS-NOTE;initial catalog=DB_HEMOPLUS;user id=sa;password=g3rm4n;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />-->
    <add name="DataContext" connectionString="data source=192.168.254.154\SQL2008R2;initial catalog=DB_HEMOPLUS_PASQUINI_092017;persist security info=True;user id=SA;multipleactiveresultsets=True;application name=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Method:

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "HelloWorld/test/{test}", BodyStyle = WebMessageBodyStyle.Bare)]
Stream HelloWorld(string test, Stream fileContents);
  • Does it need to be a Stream? It cannot be a byte[], for example?

1 answer

0


Below is an example with byte[]:

Web.config

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1"/>
  </system.web>
  <system.serviceModel>
    <services>
       <service name="WcfService1.Service1">
        <endpoint address="web" name="ajax" behaviorConfiguration="WebGetBehavior" binding="webHttpBinding" contract="WcfService1.IService1" />
        <endpoint address=""  name="soap"   binding="basicHttpBinding" contract="WcfService1.IService1" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
            <behavior name="WebGetBehavior">
          <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="WrappedRequest" />
        </behavior>
        </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <!-- 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>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

Arquivomodel class:

    public class Arquivo
    {
        public byte[] Dados { get; set; }
        public string Nome { get; set; }
        public string Extensao { get; set; }
    }

Interface Iservice:

[ServiceContract]
public interface IService1
{

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "HelloWorld/test/{test}")]
    void HelloWorld(string test, Arquivo arquivo);

}

Service class:

public class Service1 : IService1
{
    public void HelloWorld(string test, Arquivo arquivo)
    {
        System.IO.File.WriteAllBytes(@"C:\"+ arquivo.Nome+ "."+ arquivo.Extensao, arquivo.Dados);

    }
}

Client:

class Program
{
    static void Main(string[] args)
    {
        using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
        {

            var arquivo = new Arquivo()
            {
                Dados = System.IO.File.ReadAllBytes(@"C:\teste.txt"),
                Extensao = "txt",
                Nome = "teste2"
            };

            byte[] bytes = System.IO.File.ReadAllBytes(@"C:\Users\Carlos\Desktop\teste.txt");

            var json = new JavaScriptSerializer().Serialize(new { arquivo = arquivo });

            string url = "http://localhost:7169/Service1.svc/web/";

            client.BaseAddress = new Uri(url);
            client.Timeout = TimeSpan.FromMinutes(10);

            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var result = client.PostAsync("HelloWorld/test/testando", content).Result;

            var responseContent = result.Content;
            string responseString = responseContent.ReadAsStringAsync().Result;
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.