Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI route to root URL

I have a WebAPI application that is used for some RESTful operations in the database. It works great, but I want to match a route with the root URL. For example, I want to go to the root of the site and see some useful information that are dynamically generated.

Currently, I have it setup so that it follows the standard convention of api/{controller}/{action}, but how can I show this information when navigated to the root instead of something like api/diagnostics/all?

Basically what I want is, when the user navigates to the root URL, I want to route that request to TestController.Index()

I have the following setup in the WebApiConfig.cs file:

public static void Register(HttpConfiguration config)
{
    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "Index",
        routeTemplate: "",
        defaults: new { controller = "Test", action = "Index" }
    );

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional, controller = "Test" }
    );
}

And this is what my TestController.cs looks like:

[RoutePrefix("api")]
public class TestController : ApiController
{

    [Route("TestService"), HttpGet]
    public string Index()
    {
         return "Service is running normally...";
    }        
}
like image 458
hyde Avatar asked Dec 30 '15 03:12

hyde


2 Answers

You could also simply use ([Route("")]):

public class TestController : ApiController
{

    [Route(""), HttpGet]
    public string Index()
    {
         return "Service is running normally...";
    }        
}
like image 172
Martin Avatar answered Nov 11 '22 12:11

Martin


You can add a route for the default URL in WebApiConfig.cs. Here's an example where the root URL is mapped to method HomeController.Index():

config.Routes.MapHttpRoute(
    name: "Root",
    routeTemplate: "",   // indicates the root URL
    defaults: new { controller = "Home", action = "Index" }   // the controller action to handle this URL
);
like image 6
Keith Avatar answered Nov 11 '22 12:11

Keith