3

I want to take an environmental variable and prefix it to the route for all the controllers. So in Controllers I have the followings:

[ApiController]
[Route("[controller]")]
public class DashboardsController : ControllerBase
{.......}

Program.cs routing part ==>

app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();

I have tried creating a class with constant strings and putting into the Route attribute but as you know we cannot change constants, so this didn't work.

1
  • What’s the point? Nothing built in does this Commented Jul 15, 2022 at 13:38

2 Answers 2

2

The [Route] attribute implements a IRouteTemplateProvider interface, which defines a Template property that returns the route template.

If you implement a custom attribute, say [DynamicRoute], that takes an environment variable name as a parameter, you could set the Template property to a different value based on the environment variable passed in.

This works for me:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public sealed class DynamicRouteAttribute : Attribute, IRouteTemplateProvider
    {
        public DynamicRouteAttribute(string environmentVariableName)
        {
            ArgumentNullException.ThrowIfNull(environmentVariableName);

            Template = Environment.GetEnvironmentVariable(environmentVariableName);
        }

        public string? Template { get; }

        public int? Order { get; set; }

        public string? Name { get; set; }
    }

Replace [Route("[controller]")] in your controller with [DynamicRoute("yourEnvVarName")] and it will start to honor whatever you configure in your environment variable.

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

1 Comment

Thank you ! I tried it, made some changes (inheriting from RouteAttribute), and It worked!
1

After @julealgon's answer, this is the final solution.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public sealed class DynamicRouteAttribute : RouteAttribute
    {
        public DynamicRouteAttribute(string template) 
            : base($"{Environment.GetEnvironmentVariable("test")}/{template}")
        {
            ArgumentNullException.ThrowIfNull(template);
        }
    }

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.