1

ContentRootPath

I have changed the ContentRootPath to c:\images as follows.

public class Program
{
    // others are removed for simplicity.

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseContentRoot(@"c:\images")
            .UseStartup<Startup>();
}

There are only JPEG photos in c:\images.

Controller

Using DI, I can access ContentRootPath via _env as follows.

public class HomeController : Controller
{

    [HttpGet]
    public IActionResult Index()
    {
        string crp = _env.ContentRootPath;
        object[] filepaths = Directory.GetFiles(crp)
            .Select(x=>Path.GetFileName(x))
            .ToArray<string>();

        return View(filepaths);

    }


    [HttpGet]
    public FileStreamResult ViewImage(string filename)
    {
        string filepath = Path.Combine(_env.ContentRootPath, filename);

        byte[] data = System.IO.File.ReadAllBytes(filepath);

        Stream stream = new MemoryStream(data);
        return new FileStreamResult(stream, "image/jpeg");
    }
}

CSHTML

@model IList<object> 


@foreach (var item in Model)
{
    <img src="/Home/ViewImage/@item" />
}

Problem and Question

filename is always null. What is wrong and how to fix it?

Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165
  • Can you put a breakpoint at, and verify the result of `Directory.GetFiles(crp)`? – Stefan Jun 04 '18 at 18:51
  • Do you get any errors? Check out this post and see if it helps at all: https://stackoverflow.com/questions/6473811/mvc-how-to-serve-images-to-response-stream – Matt Jun 04 '18 at 18:52

1 Answers1

1

Since you are using (presumably) a default routing, your last routing parameter is id and optional.

To make your get work, you can alter your image source to a route with a named parameter:

<img src="/Home/ViewImage?filename=@item" />
Stefan
  • 17,448
  • 11
  • 60
  • 79