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

问题描述

是否有可能有一个通用的网页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>
{
   //..
}

这会是一个很好的方法?

Would this be a good approach?

毕竟,I M人云亦云的CRUD方法?我可以使用这个基类做的工作适合我?

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

这是OK?你会怎么做呢?任何更好的想法?

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 主键,一些原本字符串和其他人的GUID

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控制器来支持任何模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 15:40