【发布时间】:2015-07-02 16:12:28
【问题描述】:
而不是有两个 API 方法,一个获取所有实体并通过 ID 获取单个实体。我想将这两者合并在一起,因为它只有一行代码会发生变化(要执行的 lambda)。所以我想我不妨用一个可选参数和一个简单的 IF 语句制作一个 GET 方法,以确定参数是否不同于 0。
当我只执行一个简单的 GET 请求时,我的所有实体都没有问题,但是在 URL 末尾传递一个 ID 时,当我去调试代码时它不会被识别。
我的 URL 看起来像(服务是一个虚拟目录)
http://localhost:55985/Service/api/Operator/5
这是路由问题吗?
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
GET方法
public HttpResponseMessage Get(int machineID = 0)
{
using (DAL.Repositories.Repository<MachineOperators> machineOperatorRepo = new DAL.Repositories.Repository<MachineOperators>())
{
try
{
var operators = machineOperatorRepo.GetAll(y => y.Machine, z => z.Operator).Where(x => x.Operator.Active && x.Machine.Active);
if (machineID != 0)
{
operators = machineOperatorRepo.GetAll(y => y.Machine, z => z.Operator).Where(x => x.Operator.Active && x.MachineID == machineID);
}
}
}
}
我在方法上方使用了[HttpGet],但后来删除了它。
【问题讨论】:
-
你能也展示一下你的方法吗?
-
不,目前只是默认的
标签: c# asp.net-web-api2