Really dirty way to do this, but I am not sure if you have shorter and better options.
Library project
I am going to create custom attribute that would override RouteAttribute's template with value from config.
Firstly, since we don't have a way to use dependency injection with attributes, we need static resolver, taken from here.
using System;
namespace ClassLibrary1
{
public class AppDependencyResolver
{
private static AppDependencyResolver _resolver;
public static AppDependencyResolver Current
{
get
{
if (_resolver == null)
throw new Exception("AppDependencyResolver not initialized. You should initialize it in Startup class");
return _resolver;
}
}
public static void Init(IServiceProvider services)
{
_resolver = new AppDependencyResolver(services);
}
private readonly IServiceProvider _serviceProvider;
public object GetService(Type serviceType)
{
return _serviceProvider.GetService(serviceType);
}
public T GetService<T>()
{
return (T)_serviceProvider.GetService(typeof(T));
}
private AppDependencyResolver(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
}
}
Next thing, custom attribute that inherits from RouteAttribute
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace ClassLibrary1
{
public class DynamicRouteAttribute : RouteAttribute
{
public DynamicRouteAttribute(string template) : base(ModifyTemplate(template))
{
}
private static string ModifyTemplate(string template)
{
var config = AppDependencyResolver.Current.GetService<IConfiguration>();
var routePrefix = config.GetValue<string>("route");
return routePrefix + "/" + template;
}
}
}
And controller itself
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
namespace ClassLibrary1
{
[DynamicRoute("stuff")]
[ApiController]
public class LibraryController : ControllerBase
{
[Route("")]
[HttpGet]
public void Get(int id)
{ }
[Route("")]
[HttpDelete]
public void Delete(int id)
{ }
[Route("")]
[HttpPost]
public void Post(int id)
{ }
}
}
Parent (Web) project. Register your static resolver
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
AppDependencyResolver.Init(app.ApplicationServices);
...
}
And put your prefix value to appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"route": "someRoute"
}
Using this solution we can check all available routes. For the second web projects steps will be the same, just different value in config file.
