2

How do I pass an environment variable to an attribute?

example:

[HttpPost(**VARIABLEX**)]
public IActionResult PostCustomer()
{ 

} 
1
  • 1
    When the value of the VARIABLEX should be substituted? At the compile time or at the runtime? Commented Jan 8, 2023 at 1:26

1 Answer 1

1

If you want this to be specifically in attribute you can achieve this by a bit hackish custom route constraint:

/// <summary>
/// Matches value from "Test" environment variable 
/// </summary>
class EnvRouteConstraint : IRouteConstraint
{
    public bool Match(
        HttpContext httpContext,
        IRouter route,
        string routeKey,
        RouteValueDictionary values,
        RouteDirection routeDirection)
    {
        if (!values.TryGetValue(routeKey, out var routeValue))
        {
            return false;
        }

        var routeValueString = Convert.ToString(routeValue, CultureInfo.InvariantCulture);

        if (routeValueString is null)
        {
            return false;
        }

        return Environment.GetEnvironmentVariable("Test")
            ?.Equals(routeValueString, StringComparison.OrdinalIgnoreCase) ?? false;
    }
}

Then in services registration:

builder.Services.AddRouting(options => options.ConstraintMap.Add("fromVarTest", typeof(EnvRouteConstraint)));

And on controller:

[HttpPost("{_:fromVarTest}")]
public IEnumerable<WeatherForecast> SomeMethod()
{
}
Sign up to request clarification or add additional context in comments.

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.