【发布时间】:2014-05-19 12:31:12
【问题描述】:
我的路由配置如下:
routes.MapHttpRoute("DefaultApi2", "api/{controller}/{action}/{id}", new {id = RouteParameter.Optional}
我的控制器看起来像这样:
public class RoutineController : ApiController
{
private readonly RoutineService _routineService;
public RoutineController(RoutineService routineService)
{
_routineService = routineService;
}
[HttpGet]
[ActionName("Tags")]
public List<RoutineTag> Tags()
{
return _routineService.GetAllTags();
}
[HttpGet]
[ActionName("SingleRoutine")]
// GET api/routine/5
public RoutineViewModel SingleRoutine(int id)
{
return _routineService.GetRoutineById(id);
}
}
但是我收到了这个错误:
{"Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'Infrastructure.Api.Models.RoutineViewModel Routine(Int32)' in 'Infrastructure.Api.Controllers.RoutineController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."}
如果我将方法 SingleRoutine 更改为:
[HttpGet]
[ActionName("SingleRoutine")]
// GET api/routine/5
public RoutineViewModel SingleRoutine(int? id)
{
if (!id.HasValue)
{
return null;
}
return _routineService.GetRoutineById((int) id);
}
在浏览器中我只看到“null”。
为什么会这样?
编辑
当我输入 /api/routine/tags 时显示此错误
【问题讨论】:
-
错误出现在哪一行?我敢打赌它不在这里。
-
不抛出异常,浏览器显示此错误
-
我不知道这是否重要,但我使用 Niject 作为 IoC
-
你调用控制器的 url 是什么?试试“api/routine/SingleRoutine/5”。
-
产生此错误的请求是什么?该请求中的
id值在哪里?
标签: c# asp.net asp.net-web-api asp.net-web-api2