WebAPI URL for root URL

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

I currently have a setting so that it conforms to the standard api/{controller}/{action} conventions, but how can I show this information when navigating to the root instead of something like api/diagnostics/all ?

Basically I want when the user navigates to the root url I want to direct this request to TestController.Index()

I have the following setting 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 here is what my TestController.cs looks like:

 [RoutePrefix("api")] public class TestController : ApiController { [Route("TestService"), HttpGet] public string Index() { return "Service is running normally..."; } } 
+5
source share
3 answers

Basically I want when the user navigates to the root URL, I want to redirect this request to TestController.Index ()

In this case, make sure that you have not run your TestController.Index test with this attribute:

 [Route("TestService")] 

So what your TestController looks like:

 [RoutePrefix("api")] public class TestController : ApiController { [HttpGet] public string Index() { return "Service is running normally..."; } } 

Now just go to / or /api .

+4
source

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

 config.Routes.MapHttpRoute( name: "Root", routeTemplate: "", // indicates the root URL defaults: new { controller = "Home", action = "Index" } // the controller action to handle this URL ); 
+4
source

You can also just use ( [Route("")] ):

 public class TestController : ApiController { [Route(""), HttpGet] public string Index() { return "Service is running normally..."; } } 
+3
source

Source: https://habr.com/ru/post/1239462/


All Articles