简体   繁体   中英

Changing Route attribute value dynamically in ASP.NET CORE

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.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM