3

可能重复:
带流的 WCF Rest Webservice

我正在使用 C# 开发 WCF .NET Framework 4.0。

我用这个 Visual Studio 模板创建了这个 WCF:

在此处输入图像描述

我需要发送带有两个或三个参数的图像。这就是OperationContract我所拥有的(我要的是最后一个):

[ServiceContract]
public interface IRestServiceImpl
{
    [OperationContract]
    [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "orders/")]
    OrderContract[] allOrders();

    [OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "filteredOrders/")]
    OrderContract[] GetOrders(IdsMessage msg);

    [OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "completeFilteredOrders/")]
    OrderContract[] LoadCompleteFilteredOrders(IdsMessage msg);

    [OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "saveEReports/")]
    Boolean SaveEReports(EReportContract[] eReports);

    [OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "saveEReport/")]
    long SaveEReport(EReportContract eReport);

    [OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "UploadPhoto/{eReportId}/{imageType}")]
    Boolean UploadPhoto(string eReportId, string imageType, Stream fileContents);
}

这是Web.config

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="EReportService.RestServiceImpl" behaviorConfiguration="ServiceBehaviour">
        <endpoint address="" binding="webHttpBinding" contract="EReportService.IRestServiceImpl" behaviorConfiguration="web">
        </endpoint>
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding maxReceivedMessageSize="2097152" maxBufferSize="2097152" transferMode="Streamed"/>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <connectionStrings>

  </connectionStrings>
</configuration>

当我运行服务时,出现以下异常:

操作必须有一个类型为 Stream 的参数

如果我这样做:

[OperationContract]
[WebInvoke(Method = "POST",
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Bare,
    UriTemplate = "UploadPhoto")]
Boolean UploadPhoto(Stream fileContents);

它工作得很好,但我需要用图像发送更多数据。

此服务针对Android平板电脑应用程序公开。以下代码显示了我现在如何将图像发送到服务器:

public static Boolean sendImage(String url, String filePath)
{
    try
    {
        MultiValueMap<String, Object> formData;

        Resource resource = new FileSystemResource(filePath);

        // populate the data to post
        formData = new LinkedMultiValueMap<String, Object>();
        formData.add(OrderSpringController.FILE, resource);

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));

        // Sending multipart/form-data
        requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

        // Populate the MultiValueMap being serialized and headers in an HttpEntity object to use for the request
        HttpEntity<MultiValueMap<String, Object>> requestEntity = 
                new HttpEntity<MultiValueMap<String, Object>>(formData, requestHeaders);

        GsonHttpMessageConverter messageConverter = new GsonHttpMessageConverter();
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        messageConverters.add(messageConverter);

        // Create a new RestTemplate instance
        RestTemplate restTemplate = new RestTemplate(true);
        restTemplate.getMessageConverters().add(messageConverter);

        // Make the network request, posting the message, expecting a String in response from the server
        ResponseEntity<Boolean> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity,
                Boolean.class);

        // Return the response body to display to the user
        return response.getBody();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
    return null;
}

浏览到元数据端点 ( http://localhost:2351/RestServiceImpl.svc ) 时发生错误。

如何发送图像和参数?

4

3 回答 3

5

如果您切换到(BasicHttp 或 WSHttp)绑定,那么您可以通过组合单个数据类型来实现您的目标,包括通过属性和 Stream 对象本身的所有自定义参数。然后,您将使用消息传递样式而不是 RPC 对话。请注意 WCF DTO 装饰器的 [MessageContract] 系列。

[ServiceContract]
public interface ITransferService
{
    [OperationContract]
    RemoteFileInfo DownloadFile(DownloadRequest request);

    [OperationContract]
    void UploadFile(RemoteFileInfo request); 
}
[MessageContract]
public class DownloadRequest
{
    [MessageBodyMember]
    public string FileName;
}

[MessageContract]
public class RemoteFileInfo : IDisposable
{
    [MessageHeader(MustUnderstand = true)]
    public string FileName;

[MessageHeader(MustUnderstand = true)]
public long Length;

[MessageBodyMember]
public System.IO.Stream FileByteStream;

public void Dispose()
{ 
    if (FileByteStream != null)
    {
        FileByteStream.Close();
        FileByteStream = null;
    }
}   

}

这有必要的代码http://www.codeproject.com/Articles/166763/WCF-Streaming-Upload-Download-Files-Over-HTTP

但我强烈建议WCF:使用带有消息合同的流式传输http://blogs.msdn.com/b/carlosfigueira/archive/2011/03/25/wcf-streaming-inside-data-contracts.aspx

也是必须的:)

于 2012-11-28T09:41:54.943 回答
1

我创建了新类型并将其密封

它包含 3 个值(stream、reportid、reporttype)

下面是代码

namespace WcfService5
{

    [ServiceContract]
    public interface IService1
    {    
        [OperationContract]
        Boolean UploadPhoto(data fileContents);
    }

    [Serializable]
    public struct data 
    {
        System.IO.Stream mystream;
        string ereport;
        string reporttype;
    }
}

这是服务代码

public class Service1 : IService1
{
    public bool UploadPhoto( data value)
    {
        return false;
    }     
}
于 2012-11-28T10:00:29.103 回答
1

尝试重新排序您的参数,以便 Stream 是最后一个。

也看看这里

于 2012-11-28T09:06:03.977 回答