1

我的机器在 MS WebAPI (.net4) 上托管 RESTful 服务,并且还连接到相机。我可以请求让相机拍摄快照 (jpg) 并显示捕获的图像。奇怪的是,请求总是被称为 2x - 捕获了 2 张图像,但只有最后一张图像作为输出返回。(使用google chrome postman进行测试)

在我的服务器中:

var config = new HttpSelfHostConfiguration(string.Format("http://localhost:{0}/", port));
config.MessageHandlers.Add(new SimpleFileHandler());
config.Formatters.Add(new JpegTypeFormatter());
config.Routes.MapHttpRoute( /* the route map */

在 SimpleFileHandler

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    return base.SendAsync(request, cancellationToken);
}

一个名为 JpegMediaFormatter 的 jpeg 内容类型格式化程序:

public class JpegTypeFormatter : MediaTypeFormatter
{
    private static Type _supportedType = typeof(MemoryStream);

public JpegTypeFormatter()
{
    SupportedMediaTypes.Add(new MediaTypeHeaderValue(MediaTypeNames.Image.Jpeg));
}

public override bool CanReadType(Type type)
{
    return type == _supportedType;
}

public override bool CanWriteType(Type type)
{
    return type == _supportedType;
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
    throw new NotImplementedException();
}

private Task GetWriteTask(Stream stream, MemoryStream data)
{
    return new Task(() =>
        {
            var ms = new MemoryStream(data.ToArray());
            ms.CopyTo(stream);
        });
}

public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
    if (value == null)
    {
        //value = new byte[0];
        value = new MemoryStream();
    }
    Task writeTask = GetWriteTask(writeStream, (MemoryStream)value);
    writeTask.Start();
    return writeTask;
}

}

摄像头捕捉 RESTful 调用:

[HttpGet]
public HttpResponseMessage Capture(int width)
{ // call camera API, capture image and save as img
    var memoryStream = new MemoryStream();
    img.Save(memoryStream, ImageFormat.Jpeg);
    return Request.CreateResponse(HttpStatusCode.OK, memoryStream, 
        new MediaTypeHeaderValue(MediaTypeNames.Image.Jpeg));
}

不知何故,使用 JPEG 内容调用 new MediaTypeHeaderValue() 会导致 GET 被调用两次。如果我更改为调用其他一些 MediaType,即 application/json,则 GET 不称为 2x。

任何想法为什么会发生这种情况?

编辑:其他详细信息服务器代码:

public Server : IDisposable
{
    HttpSelfHostServer _server;
    public Server()
    {
        var config = new HttpSelfHostConfiguration("http://localhost:30019");
        config.Routes.MapHttpRoute("capture", "camera/capture/");
        _server = new HttpSelfHostServer(config);
        _server.OpenAsync().Wait();
    }
...
}

相机控制器:

public class CameraController : ApiController
{
    // camera -> variable to camera h/w
    var camera = HW.Camera;
    var img = camera.Capture();
    if(img != null)
    {
        var memoryStream = new MemoryStream();
        img.Save(memoryStream, ImageFormat.Jpeg);
        var resp = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK;
            Content = new PushStreamContent((respStream, cnt, ctx) =>
            {
                using(respStream)
                {
                    memoryStream.WriteTo(respStream);
                }
            });
        };
        resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
        return resp;
    }
}
4

1 回答 1

0

我想了解您的要求……“img”是什么类型?而且我认为您可以避免创建自定义格式化程序..下面的示例:

    [HttpGet]
    public HttpResponseMessage Capture(int width)
    { 
        HttpResponseMessage response = new HttpResponseMessage();
        response.Content = new PushStreamContent((responseStream, httpContent, transportContext) =>
            {
                using (responseStream)
                {
                    img.Save(responseStream, ImageFormat.Jpeg);

                }//closing this important!
            });
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

        return response;
    }

如果您已经有图像作为文件,那么您可以执行以下操作以返回图像:

[HttpGet]
    public HttpResponseMessage Capture(int width)
    { 
        HttpResponseMessage response = new HttpResponseMessage();
        response.Content = new StreamContent(File.OpenRead(@"C:\Images\Car.jpg"));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

        return response;
    }
于 2013-05-16T20:08:58.293 回答