如何在响应中从WCF服务返回多部分/表单数据

本文关键字:多部 返回 数据 表单 服务 WCF 响应 | 更新日期: 2023-09-27 17:50:03

我希望我的WCF服务返回多部分/表单数据。虽然响应体确实包含所需的内容,但当我想看到content -type: multipart/form-data时,响应头表明响应体是application/octet-stream。

代码以下面的单元测试开始。

    [TestMethod, Owner(TEST_AUTHOR), TestCategory("MIME Testing")]
    public void TempWcfService_PostMimeRequest_ExpectSuccess()
    {
        //Arrange
        HttpClient client = new HttpClient();
        HttpMultipartMimeForm form = new HttpMultipartMimeForm();
        form.Add("Key1", "Value1");
        form.Add("Key2", "Value2");
        //Act
        HttpResponseMessage response = client.Post(TEST_HOST_URL + "/mime-test", form.CreateHttpContent());
        response.EnsureStatusIsSuccessful();
        Stream responseStream = response.Content.ReadAsStream();
        string sResponse = responseStream.ToString();
        //Assert
        Console.Write(sResponse);
    }

上面的测试使用一个WCF服务,其接口如下所示。

namespace TempWcfService
{
    /// <summary>
    /// Interface added to support http without the WCF client class
    /// </summary>
    [ServiceContract]
    public interface ITempPing
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "ping")]
        [Description("Pings the service for availability")]
        string ping();
        [OperationContract]
        [WebInvoke(UriTemplate = "mime-test", 
                   Method = "POST",
                   BodyStyle = WebMessageBodyStyle.Bare)]
        [Description("Tests a simple MIME request")]
        Stream TestMultipartMime(Stream data);
    }
}

和实现…

namespace TempWcfService
{
    /// <summary>
    /// Implementation added to support http without the WCF client class
    /// </summary>
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class TempPing : ITempPing
    {
        public string ping()
        {
            return "TempPing ping() successful";
        }
        public Stream TestMultipartMime(Stream data)
        {
            // Re-construct the multipart/form-data content
            MultipartFormData multipartFormData = new MultipartFormData(WebOperationContext.Current.IncomingRequest, data);
            HttpMultipartMimeForm responseForm = new HttpMultipartMimeForm(multipartFormData.Items);
            responseForm.Add("ErrorCode", "Success");
            responseForm.Add("ErrorMessage", "None");
            HttpResponseMessage responseMsg = new HttpResponseMessage();
            responseMsg.StatusCode = System.Net.HttpStatusCode.OK;
            responseMsg.Content = responseForm.CreateHttpContent();
            responseMsg.Headers.Add("Accept", "multipart/form-data");
            responseMsg.Headers.ContentType = "multipart/form-data; boundary=" + multipartFormData.Boundary;
            return responseMsg.Content.ReadAsStream();
        }
    }
}

WCF似乎是"帮助我"通过覆盖在代码中指定的内容类型"应用程序/octet-stream"基于使用ReadAsStream()返回的内容。是否有一种方法来获得内容类型标头来指示多部分/表单数据?

如何在响应中从WCF服务返回多部分/表单数据

您需要设置外发上下文中的内容类型:

public Stream TestMultipartMime(Stream data)
{
    // Re-construct the multipart/form-data content
    MultipartFormData multipartFormData = new MultipartFormData(WebOperationContext.Current.IncomingRequest, data);
    HttpMultipartMimeForm responseForm = new HttpMultipartMimeForm(multipartFormData.Items);
    responseForm.Add("ErrorCode", "Success");
    responseForm.Add("ErrorMessage", "None");
    HttpResponseMessage responseMsg = new HttpResponseMessage();
    responseMsg.StatusCode = System.Net.HttpStatusCode.OK;
    responseMsg.Content = responseForm.CreateHttpContent();
    WebOperationContext.Current.OutgoingResponse.ContentType = "multipart/form-data; boundary=" + multipartFormData.Boundary;
    WebOperationContext.Current.OutgoingResponse.Headers["Accept"] = "multipart/form-data";
    return responseMsg.Content.ReadAsStream();
}

请注意,您不需要在响应中设置Accept标头-该标头用于请求,以便客户端告诉服务器它想要接收的内容类型。