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
joym8
source
to share
2 answers
Try to give your default type parameter in C # terms. Like this:
[HttpGet]
[Route("departments/{type?}")]
public List<Department> Departments(string type = null)
{
//this action is not being reached
}
+3
Tim copenhaver
source
to share
As stated in the documentation, you need to provide a default value for the type
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#optional
"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
dariogriffo
source
to share