DJ5000
DJ5000

Reputation: 93

How can I find the physical path of wwwroot, in a Razor page without a controller?

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.

Upvotes: 8

Views: 8719

Answers (2)

mnu-nasir
mnu-nasir

Reputation: 1770

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();
        }     

Upvotes: 5

pitaridis
pitaridis

Reputation: 2983

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.

Upvotes: 2

Related Questions