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?
Asked
Active
Viewed 1,692 times
0
-
Any update? Does my reply help you? – Brando Zhang Oct 21 '20 at 07:30
1 Answers
1
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:

Brando Zhang
- 22,586
- 6
- 37
- 65