I created an API using Visual Studio and removed all the content I didn't want to use. Everything's fine til now. Now I'm trying to change the default route for my API but it's just not working. I want to call localhost and I want my API to redirect to QueryController
.
My RouteConfig.cs is like this:
routes.MapRoute (
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Query", action = "Get", id = UrlParameter.Optional }
);
My QueryController.cs is like this:
public class QueryController: ApiController
{
public ResultRecord Get ([FromUri] RequestRecord request)
{
...
}
}
My Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas ();
GlobalConfiguration.Configure (WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters (GlobalFilters.Filters);
RouteConfig.RegisterRoutes (RouteTable.Routes);
}
When I call localhost:port/api/Query it works fine, but if I run only localhost:port it never reaches QueryController
. Any ideas why? I've read some other threads but I just can't change this.
You have changed the route being used for your MVC controllers, not for your Web API controllers:
routes.MapRoute (
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Query", action = "Get", id = UrlParameter.Optional }
);
Note how this route does not include api/
.
You need to change your WebApi route, something like:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "Query", id = RouteParameter.Optional }
);
This will allow you to target localhost:port/api
and get to QueryController.Get
.