Skip to main content
 首页 » 编程设计

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

2024年01月21日28webabcd

我在 Controller 中有一个 Action 方法,因此:-

[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" }); 
   } 
} 

我希望将下面的两个 url 路由到操作
api/forces 
api/forces/true 

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

请您参考如下方法:

看看Attribute Routing in ASP.NET Web API 2: Optional URI Parameters and Default Values

You can make a URI parameter optional by adding a question mark to the route parameter. If a route parameter is optional, you must define a default value for the method parameter.


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

In this example, /api/forces and /api/forces/true return the same resource.



或者,您可以在路由模板中指定默认值,如下所示:
[RoutePrefix("api/forces")] 
public class ForceController : Controller { 
   [HttpGet] 
   [Route("{showAll:bool=true}")] 
   public IHttpActionResult GetForces(bool? showAll) {...} 
}