简体   繁体   中英

ASP.Net Core doesn't recognize Request.MapPath in Razor segment

Working with ASP.Net Core is still a little new to me. I'm trying to follow a tutorial on PluralSight that details how Image Composition in .NET works.

That said, the code I'm trying to convert from ASP.Net MVC to ASP.Net Core is showing an error on Request in my Index.cshtml :

<img src="@Url.Action("ImageFromPath", new { path = Request.MapPath("~/img/1.jpg") })" />

The error is simply:

The name 'Request' does not exist in the current context.

My HomeController.cs :

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public ActionResult ImageFromPath(string path)
    {
        var ms = new MemoryStream();
        using (Bitmap bitmap = new Bitmap(path))
        {
            bitmap.Save(ms, ImageFormat.Jpeg);
        }

        ms.Position = 0;
        return File(ms, "image/jpg");
    }
}

In MVC, I can look up definition of Request that goes all the way back to WebPageRenderingBase [from metadata] , yet this does not exist in .NET Core, can anyone offer a way to get this to work?

EDIT - I later plan on using the backend ImageFromPath method to return an image from an API call, not the file system.

You could just serve the image straight from file system, unless I'm missing something.

<img src="@Url.Content("~/img/1.jpg")" alt="Some Text" />

Update

I later plan on using the backend ImageFromPath method to return an image from an API call, not the file system.

You just pass the image filename only, and resolve the full path at server-side.

<img src="@Url.Action("ImageFromPath", new { filename = "1.jpg" })" />

public class HomeController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;

    public HomeController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    public ActionResult ImageFromPath(string filename)
    {
        string path = _hostingEnvironment.WebRootPath + "/img/" + filename;
        ...
    }
}

You can inject IHostingEnvironment variable in view and rewrite code like below using Host variable:

 @using Microsoft.AspNetCore.Hosting
 @inject IHostingEnvironment Host;

 <img src="@Url.Action("ImageFromPath", new { path = Host.WebRootPath + "/img/1.jpg" })"

UPDATE:

Did not see Win's update message, his solution use the same approach, but more cleaner in terms of separation of concerns than my solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM