Search code examples
c#asp.net-core.net-corerazor-pages

Razor Pages return an Image in handler to an ``<img>`` element


In MVC, we can return an image at controller using:

[HttpGet]
public ActionResult LoadImageFile(string name)
{
    byte[] Buf = System.IO.ReadAllBytes(name);
    return File(Buf, "image/png");
}

And then in my cshtml

<img src="@Url.Content("~/myController/LoadImageFile")?name=test.jpg" />

May I know how can I do that in Razor Pages handler? I am trying something like this below and it doesn't work:

public IActionResult OnGetLoadImageFile(string name)
{
    byte[] Buf = System.IO.ReadAllBytes(name);
    return File(Buf, "image/png", name);
}

<img src="@Url.Page("~/myPage", "LoadImageFile")?name=test.png" />

Solution

  • If LoadImageFile handler is in Pages/Index.cshtml.cs,your url should be like below:

    <img src="@Url.Page("Index","LoadImageFile",new {name="test.jpg" })" />
    

    Or:

    <img src="@Url.Page("/Index","LoadImageFile",new {name="test.jpg" })" />
    

    If LoadImageFile handler is in Pages/FolderName/Index.cshtml.cs,your url should be like below:

    <img src="@Url.Page("FolderName/Index","LoadImageFile",new {name="test.jpg" })" />
    

    Or:

    <img src="@Url.Page("/FolderName/Index","LoadImageFile",new {name="test.jpg" })" />