Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET WebApi custom route
    text
    copied!<p>I have a simple Controller that is returning thumbnails, it is defined like:</p> <pre><code>public class ThumbnailsController : ApiController { public HttpResponseMessage Get(string id) { //code here } } </code></pre> <p>Everything works fine, I can access image using url <code>http://site.com/api/Thumbnails/mylogin</code></p> <p>But I would like to modify this method like so:</p> <pre><code>public class ThumbnailsController : ApiController { public HttpResponseMessage Get(string login="", int size=64) { //code here } } </code></pre> <p>Idea is to be able to call:<br/> - <code>http://site.com/api/Thumbnails/</code> - this will return current logged in user picture in default (64x64) size<br/> - <code>http://site.com/api/Thumbnails/mylogin</code> - this will return mylogin user picture in default (64x64) size<br/> - <code>http://site.com/api/Thumbnails/mylogin/128</code> - this will return mylogin user picture in 128x128 size</p> <p>My problem are routes, default route works with my unchanged method, but how should I change the default to get this working?</p> <p>I will also have other Api Controllers but only this one should have custom route.</p> <p>Here is my attempt, but it isn't working.</p> <pre><code>routes.MapHttpRoute( name: "Thumbnails", routeTemplate: "api/thumbnails/{login}/{size}", defaults: new {controller="Thumbnails", action="Get", login = RouteParameter.Optional, size = RouteParameter.Optional } ); </code></pre> <p><strong>EDIT</strong> This is my Controller with test method:</p> <pre><code>public class ThumbnailsController : ApiController { public string Get(string login="", int size=64) { return string.Format("login: {0}, size: {1}", login, size); } } </code></pre> <p>and here is my RouteConfig:</p> <pre><code>public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional} ); routes.MapHttpRoute( name: "Thumbnails", routeTemplate: "api/Thumbnails/{login}/{size}", defaults: new { controller = "Thumbnails" , login = RouteParameter.Optional, size = RouteParameter.Optional } ); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload