Search code examples
c#asp.net-mvcasp.net-mvc-routing

Routing url with asp.net


I'm new to asp.net. I want to create a web sercive using asp.net. I crated a project using this tutorial.

I have these class :

public class QRCodeItem
{        
    [Key]
    public Byte Version { get; set; }        
    public int PrintPPI { get; set; }
    public int CellSize { get; set; }
}


[Route("api/QRCode")]
[ApiController]
public class QRCodeController : ControllerBase
{
    [HttpGet]
    [Route("/CreateCode/{Version}/{PrintPPI}/{CellSize}")]
    public async Task<ActionResult<IEnumerable<QRCodeItem>>> CreateCode(Byte Version = 1, int PrintPPI = 300, int CellSize = 5)
    {
        return await _context.QRCodeItems.ToListAsync();
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<QRCodeItem>>> GetQRCodeItems()
    {
        return await _context.QRCodeItems.ToListAsync();
    }
}

I try to acces to CreateCode with this url :

https://localhost:44349/api/CreateCode?Version=1&PrintPPI=300&CellSize=2

But I'm unable to call the method. How can I call CreateCode using this url ? I can change the method, but not the url.

The url is working with :

https://localhost:44349/api/QRCode

Method GetQRCodeItems is called.


Solution

  • To use the current code

    [Route("api/QRCode")] is the base route for all actions in the controller.

    The value in the Route attribute of a method is joined on to the base route of the controller.

    So for [Route("CreateCode/{Version}/{PrintPPI}/{CellSize}")] (note the removal of the leading slash character) the full route is:

    api/QRCode/CreateCode/{Version}/{PrintPPI}/{CellSize}

    https://localhost:44349/api/QRCode/CreateCode/1/300/2

    Changing the code to match the URL

    Just drop your route down to: [Route("CreateCode")]

    This works because the actual url route ends at .../CreateCode without the query string. The parameters after the ? will be picked up from the query string.

    Extra

    Microsoft Docs - Combining routes on how to properly combine routes

    Route templates applied to an action that begin with a / don't get combined with route templates applied to the controller. This example matches a set of URL paths similar to the default route

    [Route("Home")]
    public class HomeController : Controller
    {
        [Route("")]      // Combines to define the route template "Home"
        [Route("Index")] // Combines to define the route template "Home/Index"
        [Route("/")]     // Doesn't combine, defines the route template ""
        public IActionResult Index()
        {
            ViewData["Message"] = "Home index";
            var url = Url.Action("Index", "Home");
            ViewData["Message"] = "Home index" + "var url = Url.Action; =  " + url;
            return View();
        }
    
        [Route("About")] // Combines to define the route template "Home/About"
        public IActionResult About()
        {
            return View();
        }   
    }