支持任何模型的通用 Web Api 控制器 [英] Generic Web Api controller to support any model

查看:24
本文介绍了支持任何模型的通用 Web Api 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以有一个通用的 web api 来支持您项目中的任何模型?

Is it possible to have a generic web api that will support any model in your project?

class BaseApiController<T> :ApiController
{
    private IRepository<T> _repository;

    // inject repository

    public virtual IEnumerable<T> GetAll()
    {
       return _repository.GetAll();
    }

    public virtual T Get(int id)
    {
       return _repositry.Get(id);
    }

    public virtual void Post(T item)
    {
       _repository.Save(item);
    }
    // etc...
}

class FooApiController : BaseApiController<Foo>
{
   //..

}

class BarApiController : BaseApiController<Bar>
{
   //..
}

这是一个好方法吗?

毕竟,我只是在重复 CRUD 方法?我可以使用这个基类来为我完成工作吗?

After all, i m just repeating the CRUD methods ? Can i use this base class to do the work for me?

这样好吗?你会这样做吗?有什么更好的想法吗?

is this OK? would you do this? any better ideas?

推荐答案

我这样做是为了一个小项目,目的是让一些东西启动并运行以向客户演示.一旦我了解了业务规则、验证和其他注意事项的细节,我最终不得不从我的基类中覆盖 CRUD 方法,因此它没有成为长期实现.

I did this for a small project to get something up and running to demo to a client. Once I got into specifics of business rules, validation and other considerations, I ended up having to override the CRUD methods from my base class so it didn't pan out as a long term implementation.

我遇到了路由问题,因为并非所有东西都使用相同类型的ID(我使用的是现有系统).一些表有int 主键,一些有strings,而另一些有guids.

I ran into problems with the routing, because not everything used an ID of the same type (I was working with an existing system). Some tables had int primary keys, some had strings and others had guids.

我最终也遇到了这个问题.最后,虽然我第一次做的时候看起来很流畅,但在现实世界的实现中实际使用它被证明是另一回事,并没有让我走得更远.

I ended up having problems with that as well. In the end, while it seemed slick when I first did it, actually using it in a real world implementation proved to be a different matter and didn't put me any farther ahead at all.

这篇关于支持任何模型的通用 Web Api 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆