使用web api输出图像HttpResponseMessage

lol*_*lol 29 c# asp.net-web-api

我正在尝试以下代码从asp.net web api输出图像,但响应体长度始终为0.

public HttpResponseMessage GetImage()
{
    HttpResponseMessage response = new HttpResponseMessage();
    response.Content = new StreamContent(new FileStream(@"path to image"));
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

    return response;
}
Run Code Online (Sandbox Code Playgroud)

有小费吗?

作品:

    [HttpGet]
    public HttpResponseMessage Resize(string source, int width, int height)
    {
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();

        // Photo.Resize is a static method to resize the image
        Image image = Photo.Resize(Image.FromFile(@"d:\path\" + source), width, height);

        MemoryStream memoryStream = new MemoryStream();

        image.Save(memoryStream, ImageFormat.Jpeg);

        httpResponseMessage.Content = new ByteArrayContent(memoryStream.ToArray());

        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
        httpResponseMessage.StatusCode = HttpStatusCode.OK;

        return httpResponseMessage;
    }
Run Code Online (Sandbox Code Playgroud)

Dan*_*ler 5

以下内容:

  1. 确保路径正确(duh)

  2. 确保您的路由正确.您的Controller是ImageController,或者您已经定义了一个自定义路由以支持其他控制器上的"GetImage".(你应该得到404响应.)

  3. 确保您打开流:

    var stream = new FileStream(path, FileMode.Open);

我尝试了类似的东西,它对我有用.