How to get a webroot path in Web API in ASP.Net Core?

andy - 04 Apr, 2021 7182 Views 0 Comment

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{
	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.


There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

ASP.Net Core 2.0 - HTTP Error 502.5

When you deploy your asp net Core 2 0 application you may receive the following error message which is about processing failure or HTTP error 502 5 This particular error is maybe caused by the program can t start because ...