If you need to get the webroot path in Web API in ASP.Net Core. You can utilize the IWebHostEnviroment interface by inheriting it in your Web API class controller.
Let says you have ASP.Net Project called MySampleProject and you place all the Web API files under a WebAPI folder. Here is the full code in ASP.Net Core.
namespace MySampleProject.WebAPI{ [Route("api/[controller]")] public class UploadAPIController: Controller { private readonly IWebHostEnvironment _host; private readonly IHttpContextAccessor _httpContextAccessor; public UploadAPIController(IHttpContextAccessor httpContextAccessor, IWebHostEnvironment host) { _host = host; _httpContextAccessor = httpContextAccessor; //sample variable to access the webroot path var webRoot = _host.WebRootPath; } } }
If you see above code. We inherits IWebHostEnvironment interface in our class constructor.
Inside the constructor initiation class. We set the _host variable value to the interface class.
Then in our code we can easily access the _host instance and get the WebRootPath. See the example above. We declare a variable string called webRoot and assign the value.