Home > OS >  C# Attribute parameter environment
C# Attribute parameter environment

Time:01-08

How do I pass an environment variable to an attribute?

example:

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

} 

CodePudding user response:

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()
{
}

CodePudding user response:

Just pas it as a variable

string variableX = Environment.GetEnvironmentVariable("VARIABLEX");

[HttpPost(variableX)]
public IActionResult PostCustomer()
{

}

OR

[HttpPost(Environment.GetEnvironmentVariable("VARIABLEX"))]
public IActionResult PostCustomer()
{

}
  • Related