使用IHttpActionResult返回图像

时间:2015-02-26 21:11:09

标签: asp.net-web-api2

我需要使用IHttpActionResult而不是HttpResponseMessage从WebApi返回图像。如何实现这一目标&什么是接受&内容类型标题需要传递?

谢谢!

2 个答案:

答案 0 :(得分:1)

我实际上正在寻找一个解决方案,从web api发送图像驻留在互联网上,但我使用以下代码从我的web api返回本地缩略图;

[HttpGet]
[Route("thumbnail/{userId}/{fileName}")]
public IHttpActionResult GetThumbnail()
{
        var mediaRoot = System.Web.HttpContext.Current.Server.MapPath("~/media");

        var imgPath = Path.Combine(mediaRoot, "images", userId, "thumbnail", fileName);
        var fileInfo = new FileInfo(imgPath);

        return !fileInfo.Exists
            ? (IHttpActionResult)NotFound()
            : new FileResult(fileInfo.FullName);
}

希望这有帮助

编辑:你应该创建一个自定义的IHttpActionResult来重新调整图像,

似乎我创建了一个自定义的IHttpActionResult来返回图像,这里是我从>获得此代码的帖子。 Custom IHttpActionResult

答案 1 :(得分:0)

这将是一种基本方式:

[HttpGet]
[Route("test")]
public IHttpActionResult GetImageTest()
{
    var stream = File.OpenRead(@"C:\picture.jpg");

    var response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);

    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
    response.Content.Headers.ContentLength = stream.Length;

    return ResponseMessage(response);
}