设计Web API控制器

时间:2014-02-24 07:59:32

标签: c# asp.net-web-api

在现有的LOB应用程序中,我添加了新的Web API项目。由于app中的现有层(Domain对象,DAL-ADO.NET-DataReader,BLL),我决定通过保存现有逻辑来使用Web API。

第一个问题:这是正确的方法吗?

BLL中有一个返回对象列表的方法,并接收4个参数。所有这些输入参数都可以为NULL,在这种情况下,该方法返回完整的对象列表。

第二个问题:如何为上述方法设计WEB api控制器?

public static List<DomainObject> GetTata(int? param1,int? param2, int? param3, int? param4)
{
    List<DomainObject> return = new List<DomainObject>();

    using (Context context = new Context())
    {
        return = MyDAL.GetData(param1,param2,param3,param4, context);
    }

    return return ;
}

1 个答案:

答案 0 :(得分:1)

不知道 Data 意味着什么,但在设计WebApi时,您应该在“资源”中思考(而不是在“行动”中思考)。

我不喜欢静态的方法(老实说,从来没有测试它,我不知道是否有效),但是提供响应的方法应该是实例方法(迟早你可能需要访问一些实例字段)。

不知道这四个参数是什么,但您应该考虑访问此控制器的URL。让我们假设这个控制器返回类似“客户”的东西。所以我认为的URL就像:

/api/Customers -> Get ALL customers
/api/Customers/{id} -> Get Customer of this id

其他过滤器和clausules(按顺序,分页,如果需要)通常通过查询字符串传递(即看看OData如何做到这一点)。类似的东西:

/api/Customers?name=foo -> Get ALL customers which its name starts with foo
/api/Customers?name=x&order=birthDate -> Get ALL customers which its name starts with x and ordered by birhDate.

因此,您的控制器应该在URL参数(路由和查询字符串)之间转换为DAL类所期望的参数。但是,大多数情况下暴露DAL类对WebApi所期望的相同参数并不是一个好主意。

希望这有帮助...有关详细信息,您应该提供更多信息(参数含义等等)。 ;)