0

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 :

  1. [Route("api/v1/[Controller]")] or
  2. [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.

2
  • just use both route attributes on the controller Commented Feb 3, 2020 at 7:05
  • You can't change the value of a Attribute after compilation, however, the ConditionalAttribute exists, you may be able to work something out with it Commented Feb 3, 2020 at 7:06

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Though I must agree that it may work but is there by any chance a neater solution?
The neatest solution would be to not need different routes in different circumstances, but there are reasons for everything. A somewhat neater solution may be to do what Kiksen said and not use attribute routing and instead specify the routes in the Startup.cs
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.