从ASP.NET Core中的方法属性访问通用类参数T

B12*_*ter 3 c# generics reflection asp.net-core-mvc asp.net-core

我的问题

是否有可能以某种方式T从附加到此泛型类中方法的方法属性中访问泛型类的类型参数?

一个例子

例如,说我有一个通用控制器MyBaseController处理T由子控制器扩展的某种资源类型MyChildController

public class MyChildController : MyBaseController<BlogPost>
{
  // ...
}
Run Code Online (Sandbox Code Playgroud)

现在,我正在使用Swagger记录我的API,更具体地说是Swashbuckle,因此,我要使用ProducesResponseType注释我的操作以指定操作的返回类型。这很复杂,因为ProducesResponseType需要一个Type表示操作返回值的类的参数。

public abstract class MyBaseController<T> : Controller where T : IResource
{
   [HttpGet, ProducesResponseType(T)] // <-- DOESN'T WORK!
   public async Task<IActionResult> doSomething()
   {
     // ...
   }
 }
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我需要T以某种方式解决typeof(BlogPost)

有什么想法,还是不可能?

Nko*_*osi 5

无法访问属性中的泛型。

考虑替代方法

ASP.NET Core Web API中的参考控制器操作返回类型

ASP.NET Core 2.1引入了ActionResult<T>Web API控制器操作的返回类型。它使您能够返回派生自ActionResult特定类型的类型或返回特定类型。

public abstract class MyBaseController<T> : Controller where T : IResource {
    [HttpGet]
    public async Task<ActionResult<T>> doSomething() {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

正是出于这个目的而创造的

ActionResult<T>与该IActionResult类型相比,具有以下优点 :

  • [ProducesResponseType]属性的Type属性可以被排除。
  • 隐式转换运营商支持的转换 TActionResultActionResult<T>T转换为 ObjectResult,表示return new ObjectResult(T);简化为return T;