Search code examples
c#asp.netasp.net-web-apiasp.net-mvc-routing

Remove "api" prefix from Web API url


I've got an API controller

public class MyController : ApiController { ... }

By default it is mapped to URL mysite/api/My/Method, and I'd like it to have URL without "api" prefix: mysite/My/Method

Setting controller attribute [RoutePrefix("")] didn't help me.

Are there any other ways to achieve that?


Solution

  • The default Registration is usually found in WebApiConfig and tends to look like this

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Attribute routing.
            config.MapHttpAttributeRoutes();
    
            // Convention-based routing.
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
    

    You need to edit the routeTemplate in the convention-based setup.

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Attribute routing.
            config.MapHttpAttributeRoutes();
    
            // Convention-based routing.
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
    

    Do note that if this project is shared with MVC that the reason for the api prefix was to avoid route conflicts between the two frameworks. If Web API is the only thing being used then there should be no issue.