Arun Singh
Arun Singh

Reputation: 647

Web API 2 Generic route with every controller

I am working on web api 2.0 and trying to achieve below url to access with every controller. I have created a base controller which I inherited to every controller. Now I have a scenario where I need Ping method with every controllers.

Could you please suggest to get this path?

Need below endpoint path with every controller

https://localhost/employee/Ping

https://localhost/student/Ping

Base controller

public class BaseController : ApiController
{
    [HttpGet]
    [Route("Ping")]
    public IHttpActionResult Ping()
    {
        return this.Ok(HttpStatusCode.OK);

    }
}

EmployeeController

[RoutePrefix("Employee")]
public class EmployeeController : BaseController
{
   [HttpGet]
   [Route("GetEmployee")]
   public IHttpActionResult GetEmployee()
   {
      //Implementation
      //..
   }
}

StudentController

[RoutePrefix("Student")]
public class StudentController : BaseController
{
   [HttpGet]
   [Route("GetStudent")]
   public IHttpActionResult GetStudent()
   {
      //Implementation
      //..
   }
}

Upvotes: 0

Views: 728

Answers (1)

DanielD
DanielD

Reputation: 396

Usually you will have some code that configures the routes for you (depends on the used features/framework), for example:

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

As you can see there's also a setup to include the controller's name inside the routes. For MVC Controllers each method exposed for the API Endpoint will be an action.

Using the above setup will provide TestController and it's HttpGet Method named Ping with an exmaple URL of "localhost/Test/Ping" automatically.

You can still overwrite those routes using the RouteAttribute and the same templating. So creating your BaseController with a method Ping and adding Route["{controller}/Ping"] will use the name of the used controller and replace it with the placeholder inside the Route's templating path. For example having an EmployeeController implementing your BaseController should likely lead to and Employee/Ping Url instead.

Using your given code snippets:

// hint: you can also place the Route attribute on the controller to affect all methods inside it
public class BaseController : ApiController {
    [Route("{controller}/ping")]
    public IHttpActionResult Ping()
    {
        return this.Ok(HttpStatusCode.OK);
    }
}

public class StudentController : BaseController
{
   [HttpGet, Route("students")]
   public IHttpActionResult GetStudent()
   {
      //Implementation
      //..
   }
}

(Haven't tested all of this, it's currently just theory ;) )

Btw, what's the point in having multiple ping endpoints, one should be enough?

Upvotes: 0

Related Questions