C# 向类添加[ApiController]属性

C# 向类添加[ApiController]属性,c#,asp.net-core-webapi,roslyn,asp.net-core-3.1,C#,Asp.net Core Webapi,Roslyn,Asp.net Core 3.1,我已经实现了将Asp.NETWebAPI迁移到Asp.NETCore3.1的项目。我已经开始学习Rosyln解析器。使用Rosyln,我必须将“ApiController”属性更改为类名中的属性 Sample.cs namespace TestFile.TestData.Target { public class SampleFile: ApiController { } } 进入 我关注了以下链接: . 但我不明白 请就如何使用Roslyn提出替代解决方案。

我已经实现了将Asp.NETWebAPI迁移到Asp.NETCore3.1的项目。我已经开始学习Rosyln解析器。使用Rosyln,我必须将“ApiController”属性更改为类名中的属性

Sample.cs

namespace TestFile.TestData.Target
{   
  public class SampleFile: ApiController
  {        
  }
}
进入

我关注了以下链接: . 但我不明白


请就如何使用Roslyn提出替代解决方案。

您想要了解什么?您已成功添加了
[ApiController]
没有更多额外步骤。该链接是关于通过源Generator(编写代码的代码)添加属性的,如果您只是尝试添加属性,则不需要源生成器

顺便说一句,Roslyn是c#编译器的名字。Wich用于创建整个应用程序,而不是用于向类添加属性的工具:)

如果您试图通过源代码生成器生成类,可能需要对问题进行一点编辑。

最后我得到了这个问题

Sample.cs

private void AddCustomClassAttribute(string TargetClassFile, string CustomAttributeName)
{    
    var code = File.ReadAllText(TargetClassFile);
    var updateClassFile = InsertClassAttribute(code, CustomAttributeName).GetAwaiter().GetResult();
    if (!string.IsNullOrEmpty(updateClassFile))
        File.WriteAllText(TargetClassFile, updateClassFile);           
}

private async Task<string> InsertClassAttribute(string Code, string CustomAttributeName)
{
    // Parse the code into a SyntaxTree.
    var tree = CSharpSyntaxTree.ParseText(Code);
    // Get the root CompilationUnitSyntax.
    var root = await tree.GetRootAsync().ConfigureAwait(false) as CompilationUnitSyntax;    
    var findNamespace = root.Members.Single(m => m is NamespaceDeclarationSyntax) as NamespaceDeclarationSyntax;
    // Get all class declarations inside the namespace.
    var classDeclarations = findNamespace.Members.Where(m => m is ClassDeclarationSyntax);
    // find the main class from the findNameSapce
    var findRootClass = classDeclarations.First() as ClassDeclarationSyntax;
    var addCustomAttribute = AttributeList(
                                SingletonSeparatedList(
                                    Attribute(IdentifierName(CustomAttributeName)))
                                ).NormalizeWhitespace();

    // To check whether specific attribute is present in the class or not then only insert given attribute
    if (findRootClass.BaseList?.Types.ToFullString().Trim() == CustomAttributeName)
    {
        var attributes = findRootClass.AttributeLists.Add(addCustomAttribute);
        root = root.ReplaceNode(
            findRootClass,
            findRootClass.WithAttributeLists(attributes)).NormalizeWhitespace();
        return root.ToFullString();
    }
    return null;            
}
private void AddCustomClassAttribute(字符串TargetClassFile,字符串CustomAttributeName)
{    
var code=File.ReadAllText(TargetClassFile);
var updateClassFile=InsertClassAttribute(代码,CustomAttributeName).GetAwaiter().GetResult();
如果(!string.IsNullOrEmpty(updateClassFile))
writealText(TargetClassFile,updateClassFile);
}
专用异步任务InsertClassAttribute(字符串代码、字符串CustomAttributeName)
{
//将代码解析为语法树。
var tree=CSharpSyntaxTree.ParseText(代码);
//获取根CompilationUnitSyntax。
var root=await tree.GetRootAsync().ConfigureAwait(false)为CompilationUnitSyntax;
var findNamespace=root.Members.Single(m=>m是NamespaceDeclarationSyntax)作为NamespaceDeclarationSyntax;
//获取命名空间内的所有类声明。
var classDeclarations=findNamespace.Members.Where(m=>m是ClassDeclarationSyntax);
//从FindNamesAce中查找主类
var findRootClass=classDeclarations.First()作为ClassDeclarationSyntax;
var addCustomAttribute=AttributeList(
单音分隔列表(
属性(IdentifierName(CustomAttributeName)))
).whitespace();
//要检查类中是否存在特定属性,请仅插入给定属性
if(findRootClass.BaseList?.Types.ToFullString().Trim()==CustomAttributeName)
{
var attributes=findRootClass.AttributeLists.Add(addCustomAttribute);
root=root.ReplaceNode(
findRootClass,
findRootClass.WithAttributeList(attributes)).NormalizeWhitespace();
返回root.ToFullString();
}
返回null;
}

您不了解的部分是什么?不知道如何以及在何处调用addattribute方法调用,而且SyntaxTree不包含ParseCompilationUnitOK的定义,那么如何在classAttribute中添加自定义属性是一个类。要创建自定义属性,请创建从属性继承的类,并在其名称中使用后缀“attribute”(例如公共类MyNewCustomAttribute:attribute)。申请和上面一样,只是用它装饰课堂。唯一奇怪的是,没有使用属性后缀,因此该属性会像[MyNewCustom]那样添加
private void AddCustomClassAttribute(string TargetClassFile, string CustomAttributeName)
{    
    var code = File.ReadAllText(TargetClassFile);
    var updateClassFile = InsertClassAttribute(code, CustomAttributeName).GetAwaiter().GetResult();
    if (!string.IsNullOrEmpty(updateClassFile))
        File.WriteAllText(TargetClassFile, updateClassFile);           
}

private async Task<string> InsertClassAttribute(string Code, string CustomAttributeName)
{
    // Parse the code into a SyntaxTree.
    var tree = CSharpSyntaxTree.ParseText(Code);
    // Get the root CompilationUnitSyntax.
    var root = await tree.GetRootAsync().ConfigureAwait(false) as CompilationUnitSyntax;    
    var findNamespace = root.Members.Single(m => m is NamespaceDeclarationSyntax) as NamespaceDeclarationSyntax;
    // Get all class declarations inside the namespace.
    var classDeclarations = findNamespace.Members.Where(m => m is ClassDeclarationSyntax);
    // find the main class from the findNameSapce
    var findRootClass = classDeclarations.First() as ClassDeclarationSyntax;
    var addCustomAttribute = AttributeList(
                                SingletonSeparatedList(
                                    Attribute(IdentifierName(CustomAttributeName)))
                                ).NormalizeWhitespace();

    // To check whether specific attribute is present in the class or not then only insert given attribute
    if (findRootClass.BaseList?.Types.ToFullString().Trim() == CustomAttributeName)
    {
        var attributes = findRootClass.AttributeLists.Add(addCustomAttribute);
        root = root.ReplaceNode(
            findRootClass,
            findRootClass.WithAttributeLists(attributes)).NormalizeWhitespace();
        return root.ToFullString();
    }
    return null;            
}