Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute routing with optional parameters in ASP.NET Web API

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&parameter3=value3 http://mysite/api/servicename/parameter1?parameter2=value2&parameter3=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     } } 
like image 838
sohum Avatar asked Mar 13 '14 19:03

sohum


People also ask

How do I specify a route in Web API?

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.

What is attribute routing in ASP.NET Web API?

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.

Which is optional element when you define route config in Web API?

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.


1 Answers

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 
like image 189
Kiran Avatar answered Sep 18 '22 14:09

Kiran