我的路由配置如下:
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
时会显示此错误答案 0 :(得分:5)
我相信这是WebApiConfig中的问题我有以下几行:
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional}
);
config.Routes.MapHttpRoute("CustomApi", "{controller}/{action}/{id}", new {id = RouteParameter.Optional}
);
在路线配置中
routes.MapHttpRoute("DefaultApi2", "api/{controller}/{action}/{id}", new {id = RouteParameter.Optional}
现在在WebApiConfig中我有:
config.Routes.MapHttpRoute("CustomApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional}
);
在RouteConfig中:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
它有效!
答案 1 :(得分:1)
for api / {controller} / {action} / {id} route URL api / routine / 5搜索函数(action)5不存在
更新:
您的错误消息导致失败的原因:可选参数必须是引用类型,可以为空的类型,或者声明为可选参数。“}
int不可为空,因此当您不提供其值时,它无法创建id。
答案 2 :(得分:1)
使用基于约定的路由(安装nuget包)
在您的网络API上添加定义的以下类型路线
[Route("api/routine/{id}")]