Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 845
Waldemar Avatar asked Jun 12 '16 09:06

Waldemar


1 Answers

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.

like image 89
Nkosi Avatar answered Nov 10 '22 11:11

Nkosi