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