13

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?

2
  • 2
    api word is configured in the Register method of WebApiConfig static class. Commented Jun 12, 2016 at 9:49
  • Are you using attribute routing or convention-based routing? Commented Jun 12, 2016 at 11:19

1 Answer 1

22

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I would just mention that the default AccountController has [RoutePrefix("api/Account")], so in order for this to work for this controller as well, you need to remove api/ from here as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.