7

I need to make a file list in a list, which used to be easy.. but not on Asp.Net Core 2 Razor pages. I cannot find a way to get the physical path of "Poems" which is inside "wwwroot". I found many examples using IHostingEnvironment but always in a controller. But I don't have a controller, don't need one, just the page and code behind..

Oh, how I miss WebForms!

What is the solution for a Razor Page without a controller?

Thanks in advance.

DJ5000
  • 83
  • 2
  • 8
  • Not sure if it covers your needs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files By the way, could you please describe better what the feature you are working on? Sometimes new technology provides other ways to achieve what you need different way (usually it is easier than in the previous technology version). More details will help us to propose the best solution. – Dmitry Pavlov Jan 11 '18 at 11:00

2 Answers2

5

You can use IWebHostEnvironment class. Code block is given below:

private readonly IWebHostEnvironment _webHostEnvironment;

        public HomeController(
            IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
        }

public IActionResult Index()
        {
            string rootPath = _webHostEnvironment.WebRootPath
            return View();
        }     
mnu-nasir
  • 1,642
  • 5
  • 30
  • 62
2

You can make it in Razor Page the same way you do it in a controller.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Viber.Pages
{
    public class TestModel : PageModel
    {
        private Microsoft.AspNetCore.Hosting.IHostingEnvironment _env;
        public TestModel(Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
        {
            _env = env;
        }

        public void OnGet()
        {
            // use the _env here
        }
    }
}

You can use the contractor of the PageModel to inject the IHostingEnvironment.

pitaridis
  • 2,801
  • 3
  • 22
  • 41
  • 1
    Will I have to do that on every page or is there a more... "gloal" way? – DJ5000 Jan 11 '18 at 10:47
  • You will have to do it in all pages. – pitaridis Jan 11 '18 at 10:50
  • Thank you Very Very much! :) – DJ5000 Jan 11 '18 at 10:53
  • I need to create a TestModel, like this: new TestModel(). This TestModel instance is passed to InvokeAsync when the ViewComponent in invoked, but I don't have the value for argument 'env'. – Jim S Oct 15 '18 at 02:18
  • You never call `new TestModel`, the model is instanced by the system and `IHostingEnvironment env` is injected. Check out `Dependency injection` topic. – Emaborsa Oct 23 '20 at 11:34