Getting constant value inside a cshtml file by Roslyn library

48 views Asked by At

I have an ASP.NET Core v5.0 Roslyn project. I want to get the value of a constant variable inside a cshtml file. This is a part of my cshtml:

@{
    bool isPermitted = !await HasPermission(MyConstantValue);
}

MyConstantValue is identified in another file not in cshtml:

public static class Permissions
{
    public const string MyConstantValue = "PermissionName";
}

And here is what I have tried so far:

var syntaxTree = CSharpSyntaxTree.ParseText(cshtmlCode);
var root = syntaxTree.GetRoot();
var methodInvocations = root.DescendantNodes().OfType<InvocationExpressionSyntax>();

foreach (var invocation in methodInvocations)
{
    var memberAccess = invocation.Expression as MemberAccessExpressionSyntax;
    
    if (memberAccess != null && memberAccess.Name.Identifier.ValueText == "HasPermission")
    {
        var argument = invocation.ArgumentList.Arguments.FirstOrDefault();
        if (argument != null)
        {
            var argumentValue = argument.Expression.ToString();
        }
    }
}

After running this code argumentValue becomes MyConstantValue. But I need to get PermissionName.

Actually I do this at the backend side by semanticModel.GetConstantValue method. But here I tried several ways including some semanticModel examples did not work. I get "unspecified" value in argumentValue.

Thanks in advance.

0

There are 0 answers