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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With