【问题标题】:WebApi2 ResponseType attribute of a generic type泛型类型的 WebApi2 ResponseType 属性
【发布时间】:2025-11-30 02:15:01
【问题描述】:

我有一个带有 CRUD 操作的通用 WebApi 控制器,如下所示:

public abstract class BaseController<TEntity> : ApiController where TEntity : class
{
    protected abstract DbSet<TEntity> DatabaseSet { get; }

    // GET: api/{entity}
    [Route("")]
    public IEnumerable<TEntity> GetAll()
    {
        return DatabaseSet;
    }

    // GET: api/{entity}/5
    [Route("{id:int}")]
    //[ResponseType(TEntity)] ToDo: is this possible? <---
    public IHttpActionResult Get(int id)
    {
        TEntity entity = DatabaseSet.Find(id);
        if (entity == null)
        {
            return NotFound();
        }

        return Ok(entity);
    }

    // ...
    // and the rest
    // ...
}

我的问题是关于被注释掉的 [ResponseType(TEntity)]。这条线不起作用。也不使用 typeof(TEntity)。错误是'属性参数不能使用类型参数'有没有办法让泛型类型知道 ResponseType?

谢谢! 碧玉

【问题讨论】:

    标签: generics asp.net-web-api attributes


    【解决方案1】:

    link 开始,通用属性在 C# 中是不可能的。

    我对 ResponseType 属性中的 Generic 参数做了以下变通方法,基本上是将属性添加到派生类方法中。

    public abstract class BaseApiController<TModel, TEntity> : ApiController
                                                               where TModel : class, IModel
                                                               where TEntity : IApiEntity
    {
        protected readonly IUnitOfWork _uow;
        protected readonly IRepository<TModel> _modelRepository;
    
        public BaseApiController(IUnitOfWork uow)
        {
            if (uow == null)
                throw new ArgumentNullException(nameof(uow));
            _uow = uow;
    
            _modelRepository = _uow.Repository<TModel>();
        }
    
        protected virtual IHttpActionResult Get(int id)
        {
            var model = _modelRepository.Get(m => m.Id == id);
            if (model == null)
            {
                return NotFound();
            }
            var modelEntity = Mapper.Map<TEntity>(model);
            return Ok(modelEntity);
        }
    }
    
    public class PostsController : BaseApiController<Post, PostApiEntity>
    {
        public PostsController(IUnitOfWork uow) : base(uow)
        {
    
        }
    
        [ResponseType(typeof(PostApiEntity))]
        public IHttpActionResult GetPost(int id)
        {
            return Get(id);
        }
    }
    

    【讨论】:

    • 与我所做的类似,但似乎仍然不够干燥。
    最近更新 更多