【问题标题】:Web API 2 Generic route with every controllerWeb API 2 每个控制器的通用路由
【发布时间】:2024-05-29 17:55:02
【问题描述】:

我正在开发 web api 2.0 并尝试实现以下 url 以访问每个控制器。我创建了一个基本控制器,我继承了每个控制器。现在我有一个场景,每个控制器都需要 Ping 方法。

您能否建议获得这条路径?

每个控制器都需要低于端点路径

https://localhost/employee/Ping

https://localhost/student/Ping

基础控制器

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

    }
}

员工控制器

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

学生控制器

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

【问题讨论】:

  • 您可以使用模板Route["{controller}/Ping"]将Ping Endpoint添加到不同的控制器
  • 能否提供更多的实施细节?

标签: .net asp.net-web-api2 webapi asp.net-web-api-routing


【解决方案1】:

通常您会有一些代码为您配置路线(取决于使用的功能/框架),例如:

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

如您所见,还有一个设置可以在路由中包含控制器的名称。对于 MVC 控制器,为 API 端点公开的每个方法都是一个操作。

使用上述设置将自动提供 TestController 及其名为 Ping 的 HttpGet 方法,其示例 URL 为“localhost/Test/Ping”。

您仍然可以使用 RouteAttribute 和相同的模板覆盖这些路由。因此,使用 Ping 方法创建 BaseController 并添加 Route["{controller}/Ping"] 将使用所用控制器的名称并将其替换为路由模板路径中的占位符。例如,让 EmployeeController 实现您的 BaseController 可能会导致 Employee/Ping Url 代替。

使用您给定的代码 sn-ps:

// 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
      //..
   }
}

(还没有测试所有这些,目前只是理论;))

顺便说一句,有多个 ping 端点有什么意义,一个就足够了吗?

【讨论】:

  • 根据您上面的评论,您应该阅读更多关于该主题的内容。看来你对 Routing 和 Web API 不是很熟悉,看一下here