尝试使用this article在Web API 2.0项目中创建参数可选 - 基本上使用问号语法使其成为可选项。但是当省略参数时,该动作是不可达的(404)。
通话格式:
/lists/departments : returns 404
/lists/departments/sometype : works
动作:
[HttpGet]
[Route("departments/{type?}")]
public List<Department> Departments(string type)
{
//this action is not being reached
}
如this SO post所示更改gloabal.asax.cs中注册路由的顺序没有帮助。
的global.asax.cs
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
答案 0 :(得分:3)
尝试使用C#术语为type参数指定默认值。像这样:
[HttpGet]
[Route("departments/{type?}")]
public List<Department> Departments(string type = null)
{
//this action is not being reached
}
答案 1 :(得分:1)
如文档中所述,您需要为类型
提供默认值&#34;如果路由参数是可选的,则必须为method参数定义默认值。&#34;
这应该有效
[HttpGet]
[Route("departments/{type?}")]
public List<Department> Departments(string type = null)
{
//this action is not being reached
}