Search code examples
c#asp.net-coreasp.net-core-routing

Asp Net core Controller URL parameters


I have Controller class like this:

namespace OptionsAPI.Controllers
{
    [Route("api/[controller]")]
    public class OptionsController : Controller
    {    
        HttpGet("{symbol}/{date}")]
        public IActionResult Chain(string symbol, string date)
        {
            DateTime quotedate = System.DateTime.Parse(date);
        }
    }
}

When I try to call the chain function through the URL like this:

http://127.0.0.1:5000/api/options/Chain/symbol=SPX&date=2019-01-03T10:00:00

I get this error:

FormatException: The string 'symbol=SPX&date=2019-01-03T10:00:00' was not recognized as a valid DateTime. There is an unknown word starting at index '0

It seems like "SPX" and the "date" are being concatenated as one string. What is the correct way to call this URL?


Solution

  • The given route template on the action

    [HttpGet("{symbol}/{date}")]
    

    along with the template on the controller

    [Route("api/[controller]")]
    

    expects

    http://127.0.0.1:5000/api/options/SPX/2019-01-03T10:00:00
    

    But the called URI

    http://127.0.0.1:5000/api/options/Chain/symbol=SPX&date=2019-01-03T10:00:00
    

    maps the Chain in the URL to symbol and the rest to date, which will fail when parsed.

    To get the desired URI, the template would need to look something like

    [Route("api/[controller]")]
    public class OptionsController : Controller {
    
        //GET api/options/chain?symbol=SPX&date=2019-01-03T10:00:00
        [HttpGet("Chain")]
        public IActionResult Chain(string symbol, string date) {
            //...
        }
    }
    

    Reference Routing to controller actions in ASP.NET Core

    Reference Routing in ASP.NET Core