I'm trying to use Web API 2 attribute routing to set up a custom API. I've got my route working such that my function gets called, but for some reason I need to pass in my first parameter for everything to work properly. The following are the URLs I want to support:
http://mysite/api/servicename/parameter1 http://mysite/api/servicename/parameter1?parameter2=value2 http://mysite/api/servicename/parameter1?parameter2=value2¶meter3=value3 http://mysite/api/servicename/parameter1?parameter2=value2¶meter3=value3&p4=v4
The last 3 URLs work but the first one says "No action was found on the controller 'controller name' that matches the request."
My controller looks like this:
public class MyServiceController : ApiController { [Route("api/servicename/{parameter1}")] [HttpGet] public async Task<ReturnType> Get(string parameter1, DateTime? parameter2, string parameter3 = "", string p4 = "") { // process } }
The default route template for Web API is "api/{controller}/{id}". In this template, "api" is a literal path segment, and {controller} and {id} are placeholder variables. When the Web API framework receives an HTTP request, it tries to match the URI against one of the route templates in the routing table.
As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources. The earlier style of routing, called convention-based routing, is still fully supported.
Web API uses URI as “DomainName/api/ControllerName/Id” by default where Id is the optional parameter. If we want to change the routing globally, then we have to change routing code in register Method in WebApiConfig.
Web API requires to explicitly set optional values even for nullable types...so you can try setting the following and you should see your 1st request succeed
DateTime? parameter2 = null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With