locked
Setting WebRootPath variable issue RRS feed

  • Question

  • User1295747327 posted

    Most of the tutorials showing how to get WebRootPath, but no one showing how to set it. I am getting error

    System.ArgumentNullException: Value cannot be null. (Parameter 'path1')
       at System.IO.Path.Combine(String path1, String path2)

    Here is my code

            [HttpPost("savereportfile")] 
            public async Task<IActionResult> SaveReportFile([FromForm]IFormFile file, [FromForm] WorkReportDto workReportDto)
            { 
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);
    
                var fileName = System.IO.Path.GetFileName(file.FileName);
                var filePath = System.IO.Path.Combine(_env.WebRootPath, fileName);
                if (file.Length > 0)
                {
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
    
                }

    It seems WebRootPath is null. Where i can set it? I want to create folder to upload all user images into that. how to set that path as well?

    Wednesday, January 29, 2020 6:53 AM

All replies

  • User475983607 posted

    It seems WebRootPath is null. Where i can set it? I want to create folder to upload all user images into that. how to set that path as well?

    My best guess is you are asking how to access the WebRootPath property in a controller constructor using standard ASP.NET Core dependency injection.

        public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;
            private readonly IWebHostEnvironment _env;
            public HomeController(ILogger<HomeController> logger, IWebHostEnvironment env)
            {
                _logger = logger;
                _env = env;
            }
    
            [HttpGet]
            public ActionResult Index()
            {
                return Content(_env.WebRootPath);
            }

    If you are trying to set a web root to something other than wwwroot then you need to configure the static file middleware component in the startup file..  The official docs cover the details.

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

    Wednesday, January 29, 2020 11:17 AM