简体   繁体   中英

Multi Level Asp.NET routes

I'm trying to create multiple level routes in asp.net core such as:

  • api/cities
  • api/cities/{id}
  • api/cities/date/{date}

The problem is, when I try and use anything longer than the api/cities/{id} I just get a 404.

My controller:

[Route("api/[controller]")]
    public class CitiesController : Controller
    {
        private ICityRepository _repository;

        public CitiesController(ICityRepository repository)
        {
            _repository = repository;
        }

        // GET: api/cities
        [HttpGet]
        public IEnumerable<City> Get()
        {
            IEnumerable<City> results = _repository.GetCities();
            return results;
        }

        //api/cities/date/{date}
        [HttpGet]
        [Route("date/{date}")]
        public IEnumerable<City> Get2(string date)
        {
            return _repository.GetCitiesByDate(date);
        }

        // GET api/cities/5
        [HttpGet("{id: int}")]
        public string Get(int id)
        {
            return "value";
        }
    }

What do I need to do to get longer routes to work under this controller?

Edit:

I see the documentation here: https://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

It says that you can have routes like:

  • /orders/1
  • /orders/pending
  • /orders/2013/06/16

And have all three route separately. But it doesn't seem to provide example for how you do that specifically.

I can see the problem with the route as you cannot have "/" as part of the string.

Try passing the date as 2013_06_16 not 2013/06/16 or change the route to have date/{year}/{month}/{day}

example:

[Route("api/[controller]")]
public class CitiesController : Controller
{
    private ICityRepository _repository;

    public CitiesController(ICityRepository repository)
    {
        _repository = repository;
    }

    // GET: api/cities
    [HttpGet]
    public IEnumerable<City> Get()
    {
        IEnumerable<City> results = _repository.GetCities();
        return results;
    }

    //api/cities/date/2016/06/16
    [HttpGet]
    [Route("date/{year}/{month}/{day}")]
    public IEnumerable<City> Get2(string year,string month,string day)
    {
        string date = year + "/" + month + "/" + day;
        return _repository.GetCitiesByDate(date);
    }


    // GET api/cities/5
    [Route("{id: int}")]
    [HttpGet]
    public string Get(int id)
    {
        return "value";
    }

      //api/cities/pending
    [Route("{text}"]
    [HttpGet]
    public string Get(string text)
    {
        return "value";
    }
}

Hope this help.

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