返回图像 url 作为 Web api 2 查询的结果

问题描述 投票:0回答:1

编辑: 我已经更新了控制器来获取流资源,但有些它仍然不起作用

public class ResourcesController : Controller
{
    public string Directory = @"D:\Desktop\MusicDatabase\Image\";

    [HttpGet]
    [Route("Image/{type}/{id}")]
    public HttpResponseMessage Image(string type, string id)
    {
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
        var url = Path.Combine(Directory, type, id + ".jpg");
        byte[] fileData = System.IO.File.ReadAllBytes(url);
        MemoryStream ms = new MemoryStream(fileData);
        httpResponseMessage.Content = new StreamContent(ms);
        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
        return httpResponseMessage;
    }     
}

它返回一个字符串,而不是资源文件

enter image description here

当我调试时,“url”变量是

"D:\\Desktop\\MusicDatabase\\Image\\song\\2.jpg"

旧:

我有2个项目:1个用于服务器的Web api2,1个用于客户端的WP8应用程序。

服务器包含数据库,我可以链接到外部文件资源

e.x 带有 IMAGE 列的歌曲表,我将这张图片存储在桌面中

public partial class Song
{    
    public int Id { get; set; }        
    public string NAME { get; set; }

    private string _IMAGE;
    public string IMAGE 
    { 
        get
        {
            return Helper.Helper.ConcatDirectory(_IMAGE);
        }
        set
        {
            _IMAGE = value;
        }
    }

在我的数据库中,我仅通过索引存储“IMAGE”列(如“Song .jpg”),然后当我有一些查询需要处理时,我通过此返回完整的URL

public class Helper
{
    public static string Directory = "D:\\Desktop\\MusicDatabase\\";
    public static string ConcatDirectory(string input)
    {
        return string.Concat(Directory, input);
    }
}

当我在网络浏览器中尝试查询时,此 URL 将返回存储在我的电脑中的文件

enter image description here

但是我的 WP8 应用程序无法显示此图像(使用模拟器调试)。 虽然我不想将此资源存储在我的项目中,但是是否可以在此处返回这些图像? (稍后任何不同的文件类型,例如歌曲、视频......)

c# windows-phone-8 asp.net-web-api2
1个回答
0
投票

请更换

httpResponseMessage.Content = new StreamContent(ms);

httpResponseMessage.Content = new ByteArrayContent(ms);

编辑:

我真的认为你应该尝试理解其他 SO 用户的以下建议:

1)在 ASP.NET WebAPI 中处理静态图像:https://stackoverflow.com/a/12559507/2310818

© www.soinside.com 2019 - 2024. All rights reserved.