Home > Blockchain >  ASP.NET CORE - Get API URL
ASP.NET CORE - Get API URL

Time:03-08

How can I get my API URL (only API URL).

In development mode https://localhost:44372/

In production mode: https://{{ server api url }}

This is because I want to store full path file in Database some like this:

https://localhost:44372/files/licenceFiles/1234.png

CodePudding user response:

Define both URL's in appsettings.json:

{
    "ApiUrl_local": "https://localhost:xxx",
    "ApiUrl_web": "https://website.com";
}

Then use IWebHostEnvironment to check for development mode and retrive the relevant setting:

public class ApiConfig
{
    public IWebHostEnvironment Environment { get; }
    public IConfiguration Configuration { get; }


    public ApiConfig(IWebHostEnvironment environment, IConfiguration configuration)
    {
        Environment = environment;
        Configuration = configuration
    }

    public string ApiURL => Environment.IsDevelopment() ? 
    Configuration["ApiUrl_local"] : Configuration["ApiUrl_web"];
}

CodePudding user response:

This depends on where you configure your production Url. There are roughly half a dozen places, where you can store them out of the box.

LazZiya has given you an approach that works just fine locally, but hits some limitations, once you exceed the scenario, where there is only dev and prod.

If you configure them in your appsettings.json and as an environment variable, the environment variable take have precedence. If your app is going to be containerized, chances are, that most of these values will be set using einvironment variables.

To read those use Environment.GetEnvironmentVariable("ASPNETCORE_URLS"), which would give you the internal urls Kestrel is listening on. public addresses, will probably have a different key - but you get the idea.

You can read up on this here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0

  • Related