【问题标题】:Optional Parameter not being recognised可选参数未被识别
【发布时间】: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


【解决方案1】:

您应该将方法签名更改为public HttpResponseMessage Get(int id),因为在您的方法中找不到{id}

【讨论】:

  • 正是问题所在,我知道这会很愚蠢。有时,发现你变得盲目的错误只是额外的一双眼睛。谢谢:)
猜你喜欢
  • 2023-03-25
  • 1970-01-01
  • 2021-09-28
  • 2020-07-16
  • 2012-02-28
  • 1970-01-01
  • 2013-09-11
  • 2021-12-22
  • 1970-01-01
相关资源
最近更新 更多