How to assign base path of API URL in config file?

1.9k Views Asked by At

I have an ASP.NET core REST API service with .net core 3.1 version. I want to create a common variable in appsettings.json or other config files for a particular part of the URL of API. For example, if my URL is like this http://localhost:31660/Inventory/v1.0/{Id}/data here the/Inventory/v1.0 will be common for every request coming to methods of this controller. Currently, it is set in the controller. Is there any way to put that part in the config file once and get that variable whenever required to set it?

1

There are 1 best solutions below

0
On

According to your description, I suggest you could consider using custom route attribute to achieve your requirement.

You could create a static class to read the appsettings and then pass the {Id}/data as parameter to the custom route attribute class to achieve your requirement.

More details, you could refer to below codes:

appsettings.Development.json:

  "apitemplate": "Inventory/v1.0/"

MyApiControllerAttribute class:

public static class AppSettingsConfig
{
    public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
       .SetBasePath(Directory.GetCurrentDirectory())
       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
       .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
       .Build();
}
public class MyApiControllerAttribute : Attribute, IRouteTemplateProvider
{
  

    public MyApiControllerAttribute(string _route) {

       var re = AppSettingsConfig.Configuration.GetValue<string>("apitemplate");

        route = re +_route  ;
        //route = re ;

    }

    public string route { get; set; }

    public string Template => route;
    public int? Order => 0;
    public string Name { get; set; }
}

Usage:

    [MyApiController("{Id}/data")]
    public FileResult StreamVid(string Id)
    {
         return OK();
    }

Result:

enter image description here