使用路由属性将多个 URL 映射到 ASP.NET WebAPI 2 中的同一操作

本文关键字:WebAPI NET 操作 ASP 属性 路由 映射 URL | 更新日期: 2023-09-27 18:36:17

我在控制器中有一个操作方法,因此:-

[RoutePrefix("api/forces")]
public class ForceController : Controller
{
   [HttpGet]
   [Route("{showAll?}")]
   public IHttpActionResult GetForces(bool? showAll)
   {
       IEnumerable<Force> forces=  forceRepository.GetAll().ToList();
       if(!showAll)
        {
            forces = forces.ToList().Where(u => u.IsActive);
        }
       return Ok(new { data= forces, message = "The forces are with you" });
   }
}

我希望将下面的两个网址都路由到操作

api/forces
api/forces/true

我认为当前的路由属性会起作用,但它仅适用于第二个网址,即 api/forces/true 而不是第一个。

使用路由属性将多个 URL 映射到 ASP.NET WebAPI 2 中的同一操作

查看 Web API 2 中的属性路由 ASP.NET:可选 URI 参数和默认值

可以通过向 路由参数。如果路由参数是可选的,则必须定义 方法参数的默认值。

[RoutePrefix("api/forces")]
public class ForceController : Controller {
   [HttpGet]
   [Route("{showAll:bool?}")]
   public IHttpActionResult GetForces(bool? showAll = true) {...}
}

在此示例中,/api/forces/api/forces/true 返回相同的资源。

或者,您可以在路由模板中指定默认值,如下所示:

[RoutePrefix("api/forces")]
public class ForceController : Controller {
   [HttpGet]
   [Route("{showAll:bool=true}")]
   public IHttpActionResult GetForces(bool? showAll) {...}
}

您可以使用默认的路由[Route()]这将强制通过查询字符串传递showAll参数。那会接受

/api/forces
/api/forces?showAll=true
/api/forces?showAll=false
您需要

showAll 参数提供一个值,因为它不是可选的(可为空不算在内)。将其设置为可选应该可以解决问题。

[HttpGet]
[Route("{showAll?}")]
public IHttpActionResult GetForces(bool? showAll = null)
{
    ...
}