stream - 为什么这个流媒体服务示例中的响应内容为空?

标签 stream asp.net-web-api .net-4.5 httpresponse

我真的需要一些帮助来理解为什么这个单元测试失败。我怀疑这是由于我处理流的方式造成的。我有许多其他测试成功地使用了此自托管服务器设置,但它们都读取返回字符串等原语的服务。

这是有问题的测试:

using System.Net.Http;
using System.Threading;
using System.Web.Http.SelfHost;
using AttributeRouting.Web.Http.SelfHost;
using NUnit.Framework;

[TestFixture]
public class StreamControllerTests 
{
    [Test]
    public void Can_get_simple_streaming_service_to_respond()
    {
        using (var config = new HttpSelfHostConfiguration("http://in-memory"))
        {
            config.Routes.MapHttpAttributeRoutes();
            using (var server = new HttpSelfHostServer(config))
            {
                // I get the same behavior if I use HttpClient
                using (var client = new HttpMessageInvoker(server))
                {
                    using (var request = new HttpRequestMessage(HttpMethod.Get, "http://in-memory/stream/notepad"))
                    {
                        using (HttpResponseMessage response = client.SendAsync(request, CancellationToken.None).Result)
                        {
                            Assert.IsNotNull(response.Content);
                            // FAILS, content length is 0
                            Assert.Greater(response.Content.Headers.ContentLength, 0); 
                        }
                    }
                }
            }
        }

这是提供测试的 Controller :

using System;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AttributeRouting.Web.Mvc;
using MyUnitTests.Properties;

[GET("stream/notepad")]
public HttpResponseMessage StreamAnImageFromResources()
{
    var imageStream = new MemoryStream(); // closed when stream content is read
    Resources.a_jpeg_in_resources.Save(imageStream, ImageFormat.Jpeg);
    try
    {                               
        HttpResponseMessage response = Request.CreateResponse();
        // at this point, imageStream contains about 120K bytes
        response.Content = new StreamContent(imageStream); 
        return response;            
    }
    catch (Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, e);
    }
}

最佳答案

我没有发现任何真正的错误,但您的测试比需要的更复杂。

试试这个,

[Test]
public void Can_get_simple_streaming_service_to_respond2()
{
    var config = new HttpConfiguration();
    config.Routes.MapHttpAttributeRoutes();
    var server = new HttpServer(config);

    var client = new HttpClient(server);

    var request = new HttpRequestMessage(HttpMethod.Get, "http://in-memory/stream/notepad");

    HttpResponseMessage response = client.SendAsync(request, CancellationToken.None).Result;

    Assert.IsNotNull(response.Content);
    // FAILS, content length is 0
    Assert.Greater(response.Content.Headers.ContentLength, 0);
}

编辑:在评论中,Darrel 给了我真正的答案,为了可见性,我将其移至答案正文:

Check the position of your image stream after doing Save. You need to reset it back to 0 before passing to StreamContent. Also, you might want to consider doing GetManifestResourceStream instead, it will save copying the bytes into managed memory.

关于stream - 为什么这个流媒体服务示例中的响应内容为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18522120/

相关文章:

c# - MVC/EF6/WebApi2 应用程序中 DbContext 使用的正确模式

c# - 如何使用 async/await 实现命令模式

php - 使 stream_socket_server 在第一次收到数据包后保持功能

asp.net-mvc-4 - Web API ActionFilterAttribute 可以访问模型吗?

node.js - NodeJS - 为什么在 .on ('readable' ) 事件中从可读流中读取数据时使用 while 循环

c# - 依赖注入(inject)/SOLID 担忧

c# - WPF 文本 block 不会在运行时显示属性更改

asp.net-web-api - Web API 和 .NET 4.5 : Claims and rights

java - 使用 PrintWriter 通过 Java 套接字发送数据不起作用

scala - Scala 中的无限流