简体   繁体   中英

Map multiple urls to the same action in ASP.NET WebAPI 2 using routing attributes

I have an action method in a controller thus:-

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

I will like both urls below to be routed to the action

api/forces
api/forces/true

I thought the current route attribute will work, but it only works for the second url ie api/forces/true and not the first. api/users.

Have a look at 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.

Alternatively, you can specify a default value inside the route template, as follows:

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

You could just use the default route [Route()] which would force the showAll parameter to be passed via querystring. That would accept

/api/forces
/api/forces?showAll=true
/api/forces?showAll=false

You need to supply a value to the showAll parameter because it is not optional (being nullable doesn't count). Making it optional should fix the problem.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM