4

I'm trying to map my urls that look like /action-figure/ to the ActionFigureController. i.e., have my url be hyphen separated for the controllers.

Something like this answer exactly, but for WebApi instead of MVC routing.

How do I configure my urls in WebApi please?

Almost all google search directs me to MVC routing configurations and I am not able to find the equivalent of it for:

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

as MvcRouteHandler doesn't apply to this and I am not sure where to even pass in the custom route config.

Community
  • 1
  • 1
LocustHorde
  • 6,361
  • 16
  • 65
  • 94

1 Answers1

2

While it might not be possible to set multiple routes as in ASP.NET MVC, try to go for Attribute Routing to make use of easy to use annotations for specifying routes.

To enable attribute routing you need to set this in your Registermethod:

config.MapHttpAttributeRoutes();

That gives you the convenience of setting the routes for each method:

[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }

Also, RoutePrefix allows to avoid repetitively providing the whole path:

[RoutePrefix("api/books")]
public class BooksController : ApiController
{
    // GET api/books
    [Route("")]
    public IEnumerable<Book> Get() { ... }

    // GET api/books/5
    [Route("{id:int}")]
    public Book Get(int id) { ... }

    // POST api/books
    [Route("")]
    public HttpResponseMessage Post(Book book) { ... }
}

EDIT Coming back to your comment:

Have a look at this answer and the way the DefaultHttpControllerSelector is derived from and filled with some logic:

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Dispatcher;

public class ApiControllerSelector : DefaultHttpControllerSelector
{
    public ApiControllerSelector (HttpConfiguration configuration) : base(configuration) { }

    public override string GetControllerName(HttpRequestMessage request)
    {
        // add logic to remove hyphen from controller name lookup of the controller
        return base.GetControllerName(request).Replace("-", string.Empty);
    }
}

To make this work you then need to specify the custom ApiControllerSelector in the config like this:

config.Services.Replace(typeof(IHttpControllerSelector),
            new ApiControllerSelector(config));
rdoubleui
  • 3,554
  • 4
  • 30
  • 51
  • hi, thanks, is there no way to globally configure, with a bit of logic, to turn camel case controllers into hyphen seperated urls? – LocustHorde Jan 07 '16 at 15:46
  • See updated answer, there's a way at least to intercept the request and alter the controller parameter there. – rdoubleui Jan 07 '16 at 16:15