Getting Root / Base Path in ASP.NET Core 3.0 (IIS)

on Monday, December 2, 2019

In my mind a root / base path for an IIS application looks something like this:

https://my.host.com/some/subdir

That format contains the schema://host/base-path

For most web applications, this information isn’t important. And, for the most part, you should try to develop your applications to be agnostic to where it’s hosted. To do this you can use techniques like always using relative pathing in your web applications links (<a href=”../something/relative.html”>) and web api results. Of course, if you know a link is pointing to a resource outside of your application, then using an absolute path would make sense.

However, using relative paths isn’t always possible and sometimes you will need to create an absolute path for your local application. I’ve run into this scenario when a nuget package or submodule wasn’t designed with relative paths in mind and they require an absolute Uri/path as input.

When I googled for how to get the base path within an Asp.Net Core 3.0 application today, the top results where focused on getting the base path of a request. Which is really easy. The HttpRequest/Message will contain that information and it’s always at your fingertips. But the scenario I had in mind was during Startup.cs, specifically during the .Configure(IApplicationBuilder app, IWebHostEnvironment env) method.

There is a good stackoverflow post, How to get base url wihtout accessing a request, which demonstrates how to get the information in ASP.NET Core 2.X. It showed that there is an internal feature called, IServerAddressesFeature, which contains the full root / base path information (example at the start of the post). In ASP.NET Core 2.X, that service/feature was accessible from the IWebHost object that could be found in the Program.cs class.

In 3.0, IWebHost has been replaced by IHost and the .ServerFeatures property is not available on it. But, that’s because it’s even easier to get ahold of. When the IHost.Run() method is called in Program.cs, it will (eventually) call Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env). And, the ServerFeatures property is exposed on the IApplicationBuilder object. So, you can retrieve the IServerAddressesFeature information directly within the .Configure method.

For example:

And a full example:

0 comments:

Post a Comment


Creative Commons License
This site uses Alex Gorbatchev's SyntaxHighlighter, and hosted by herdingcode.com's Jon Galloway.