Reputation: 13335
I want to define two routes. One is simply a get request to the web root, e.g. http://localhost
and the second is a get request with one parameter, e.g http://localhost/{sport
}. I can get the 1st route working ok, but not the 2nd. I have tried many variations. This is one of them:
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace PricingBridge.RestService
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "aRoute",
routeTemplate: "{myParam}",
defaults: new { controller = "My", myParam = UrlParameter.Optional });
}
}
public class MyController : ApiController
{
public string Get()
{
return "1";
}
public string Get(string myParam)
{
return "2";
}
}
}
Upvotes: 1
Views: 1201
Reputation: 13335
Turns out I was using the wrong class. I should have been defining the routes in WebApiConfig, not RouteConfig.
The solution for my requirements is as follows (ignore the return values):
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute("DefaultApi", "{sport}", new { controller = "bridge", sport = RouteParameter.Optional });
}
}
public class BridgeController : ApiController
{
public IEnumerable<RestItem> GetSports()
{
return new[] { new RestItem("sport1", "relation") };
}
public IEnumerable<RestItem> GetFixtures(string sport)
{
return new[] { new RestItem(sport + "/fixture", "relation") };
}
}
Upvotes: 0
Reputation: 8091
Your routing configuration seems fine.
Try to change UrlParameter
to RouteParameter
, when it doesn't help try to make your own controller selector for diagnostics, just for intercepting to see what controller calls there and .
var config = GlobalConfiguration.Configuration;
config.Services.Replace(typeof(IHttpControllerSelector), new MyControllerSelector(config))
or the same with action selector IHttpActionSelector. It will let you see what controller or actions are exactly selected for your calls.
Upvotes: 0
Reputation: 81660
Instead of UrlParameter.Optional
, use RouteParameter.Optional
.
Former is MVC and latter is Web API.
Upvotes: 3