简体   繁体   English

在 ASP.NET CORE 中动态更改路由属性值

[英]Changing Route attribute value dynamically in ASP.NET CORE

I am looking for a way to grammatically change the value of Route attribute.我正在寻找一种在语法上更改 Route 属性值的方法。

I have a scenario where the api route should be either :我有一个场景,其中 api 路由应该是:

  1. [Route("api/v1/[Controller]")] or [Route("api/v1/[Controller]")]
  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.我尝试在 Base Controller 中添加一个变量,但意识到我无法在 Route 属性中访问它。

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 )这也是您不能使用控制器类中的变量作为参数的原因(除非它是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) (您可能希望将其更改为if RELEASE并更改为路由)

You can do this in your startup.cs您可以在您的 startup.cs 中执行此操作

app.UseMvc(routes =>
{
   routes.MapRoute("default", "api/{controller=Home}/{action=Index}/{id?}");
});

Simply make a if statement for debug.只需为调试做一个 if 语句。

app.UseMvc(routes =>
{
   routes.MapRoute("default", "api/xyz/{controller=Home}/{action=Index}/{id?}");
});

Or UseControllers or whatever you are using.或 UseControllers 或您正在使用的任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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