29

次のコードを使用して、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;
}

任意のヒント?

動作:

    [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;
    }
4

2 に答える 2

5

次のとおりです。

  1. パスが正しいことを確認してください(当然)

  2. ルーティングが正しいことを確認してください。コントローラが ImageController であるか、他のコントローラで「GetImage」をサポートするカスタム ルートを定義しています。(これに対して 404 応答が返されるはずです。)

  3. ストリームを開いていることを確認します。

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

私は似たようなことを試しましたが、それは私にとってはうまくいきます。

于 2012-12-18T15:47:10.977 に答える
2

ByteArrayContent の代わりに StreamContent クラスを使用して、ストリームをより効率的に処理することもできます。

于 2013-10-19T19:38:01.920 に答える