ASP.NET Web Api 2 - Attribute Based Routing - How do I force a parameter to query string only?


I am working on a Web Api 2 project and I am using attribute based routing. Here is a sample route:

<pre class="lang-csharp prettyprint-override">[Route("{id:int}", Name = "GetEmployeeById")] [HttpGet] public IHttpActionResult GetEmployee(int id) { ... }

This works with the following URLs:

<ul><li>://host/employee/12345</li> <li>://host/employee?id=12345</li> </ul>

What I would prefer is that the first form (the parameter in the URI), would not be allowed, and only the second form (query string) would work.

<h3>What I've Tried</h3>

Mostly, I've tried searching the web for a way to make this work, and I'm not finding much.

<a href="http://attributerouting.net/#route-constraints" rel="nofollow">This page talks about route constraints</a> but this syntax doesn't seem to work (anymore?).

<a href="http://forums.asp.net/t/1920979.aspx?Web%20Api%202%20preview%20and%20Attribute%20Routing%20allowing%20querystrings%20" rel="nofollow">This page</a> doesn't actually prevent the URI form from working.


There is an attribute called "[FromUri]" that you can use to decorate a method parameter, and the model binder will try to look for that parameter from the Querystring, it may not help you with this scenario but it is good to know about it, so in case you want to pass a search options for example to a Get method.

<ul><li><a href="http://msdn.microsoft.com/en-us/library/system.web.http.fromuriattribute(v=vs.118).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.web.http.fromuriattribute(v=vs.118).aspx</a></li> <li><a href="http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api" rel="nofollow">http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api</a></li> </ul>

Hope that helps.


Couple of ways to achieve this. Here are some options

<ol><li>Rename parameter to something else than id (eg. employeeId).</li> <li>

Change the default routing configuration in WebApiConfig:

//Default configuration, you can see here the "id" parameter which enables action/id matching config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //It should look like this config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}" ); </li> </ol>

Also you can do it with custom attributes.


Actually, I was wrong about my original code. The query string parameter did not work with the route I specified. Instead, I could do this:

<pre class="lang-csharp prettyprint-override">[Route("", Name = "GetEmployeeById")] [HttpGet] public IHttpActionResult GetEmployee(int id) { ... }

And this will do what I want. It must be getting the name id from the function's parameter list.

Unfortunately, this means I can't put a constraint on it anymore, but I guess I can just validate within the function.


  • What is the behaviour of FS = “ ” in GNU Awk 4.2?
  • Logging with AOP in .net
  • Handling “If-None-Match” header with angular resouce?
  • Cross-Origin Request Blocked with CORS headers present
  • Insert null in a database
  • SVG Fill Width to Child Elements
  • C++ stl pop doesn't return [closed]
  • How to remove last utf8 char of a python string
  • Unable to set a breakpoint on main while debugging a program compiled with Rust 1.10 with GDB
  • Doctrine2 inverse persistance not working in nested forms
  • Changing media screen makes div overlay
  • ZipList with Scalaz
  • Alamofire and Reachability.swift not working on xCode8-beta5
  • Consuming a WCF service in a Java Client using wsHttpBinding
  • jQuery: add elements until a particular height is reached
  • Question about instantiating object
  • Bash if statement with multiple conditions
  • UWP/C# - Issue with AQS and USB Devices
  • How to make JSON.NET deserialize to Microsoft Date Time?
  • Tamper-proof configuration files in .NET?
  • one Local Olampyad Questions on Informatic in 2011
  • ActiveRecord query for a count of new users by day
  • Can you perform a UNION without a subquery in SQLAlchemy?
  • Email verification using google app script and google forms
  • PostgreSQL Query without WHERE only ORDER BY and LIMIT doesn't use index
  • Finding past revisions of files in StarTeam w/ .NET SDK / C#
  • htaccess rewriting URLs with multiple forward slashes
  • 'TypeError' while using NSGA2 to solve Multi-objective prob. from pyopt-sparse in OpenMDAO
  • Display Images one by one with next and previous functionality
  • Web-crawler for facebook in python
  • R: gsub and capture
  • AT Commands to Send SMS not working in Windows 8.1
  • jqPlot EnhancedLegendRenderer plugin does not toggle series for Pie charts
  • Comma separated Values
  • A cron job substitute?
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • SQL merge duplicate rows and join values that are different
  • apache spark aggregate function using min value
  • Sorting a 2D array using the second column C++
  • How to load view controller without button in storyboard?