I have an asp.net core web api, which I can start from the command line (on linux hosts)
dotnet MyWebApi.dll
This will start some webserver that listens on localhost:5000
(per default).
Let's assume I have a ValuesController
that listens to path /values/
. Thus I can get my values from http://localhost:5000/values/
, all good.
What I need now is to add a prefix api
for all the local paths in the api, so the values controller would respond on: localhost:5000/api/values
.
I can't find an elegant way to do this.
Obviously I could change it in the controller's route configuration - but that's very redundant and requires a lot of changes, as we have many controllers, and we use [Route(..)]
attributes on the controllers themselves.
I've seen the applicationUrl
property in the launchsettings.json
file in my webapi project. Apparently it contains the configuration used for the Visual Studio debugging/launching. Adding a prefix there (through project properties > debug) works fine and does exactly what I need, but that only works for starting it from VisualStudio (i.e. dotnet run
). In the production environment I only have the dotnet publish
artifacts available - the launchsettings.json
file is not copied over there and there seems no way to provide such a file to the dotnet [assembly]
launch command (like with dotnet run).
A bit of background for why I need this:
The pattern of having the api controllers listen at /
comes from IIS, because there it's common to add apps in subfolders of sites, which handles the path prefixing part. I now deploy my app with docker and the api has its own container, where it's started with the above command - thus the prefix is missing and I need to add it back somehow.
I found a solution that does the trick, in Startup.cs
I added UseBasePath
:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ..
app.UsePathBase(new PathString("/api"));
app.UseMvc();
}
This allows getting the values from localhost:5000/api/values
and localhost:5000/values
. I don't really need or like this ambiguity, but it solves my problem for now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With