Web 2.0 API action call with [Route] attribute with optional return 404 not found?
Trying to make a parameter optional in a Web API 2.0 project using this article - basically using a question mark the syntax to make it optional. But the action is not available (404) when the parameter is omitted.
Call format:
/lists/departments : returns 404 /lists/departments/sometype : works
Act:
[HttpGet]
[Route("departments/{type?}")]
public List<Department> Departments(string type)
{
//this action is not being reached
}
Changing the registration order of the routes in gloabal.asax.cs as shown in this SO post did not help.
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);
}
}
+3
source to share
2 answers
As stated in the documentation, you need to provide a default value for the type
"If the route parameter is optional, you must define a default value for the method parameter."
This should work
[HttpGet]
[Route("departments/{type?}")]
public List<Department> Departments(string type = null)
{
//this action is not being reached
}
+1
source to share