Reputation: 5539
I am looking for a way to grammatically change the value of Route attribute.
I have a scenario where the api route should be either :
[Route("api/v1/[Controller]")]
or[Route("api/xyz/v1/[Controller]")]
based on whether I am running it in debug mode or not.
[Route("api/v1/[Controller]")]
[ApiController]
public class MyController : BaseController
{
}
I tried adding a variable in Base Controller but realized that I can't access it in Route attribute.
Upvotes: 0
Views: 2318
Reputation: 7855
You cannot change the value of an attribute after compilation, as attributes are compile time constants. That's also why you can't use a variable from you controller class as a parameter (unless it is const
)
Instead, you can use preprocessor directives to do this like so
#if DEBUG
[Route("api/v1/[Controller]")]
#else
[Route("api/xyz/v1/[Controller]")]
#endif
(You may want to change it around to if RELEASE
and also change to routes)
Upvotes: 4
Reputation: 1767
You can do this in your startup.cs
app.UseMvc(routes =>
{
routes.MapRoute("default", "api/{controller=Home}/{action=Index}/{id?}");
});
Simply make a if statement for debug.
app.UseMvc(routes =>
{
routes.MapRoute("default", "api/xyz/{controller=Home}/{action=Index}/{id?}");
});
Or UseControllers or whatever you are using.
Upvotes: 0