Routes in ASP.net Core API

70,294

Solution 1

Try this. You can put a common route prefix on the controller.

[Route("api/[controller]")]
public class BXLogsController : Controller {
    //GET api/BXlogs/id/blah
    [HttpGet("ID/{id}", Name = "GetL")]
    public IActionResult GetById(string id) { ... }

    //GET api/BXlogs/api/blahapi
    [HttpGet("API/{apiname}", Name = "GetLAPI")]
    public IActionResult GetByAPI(string apiname) { ... }
}

read up on attribute routing here Routing to Controller Actions

Solution 2

In case if you're planning to have a custom action name similar to web API's.

 [Route("api/[controller]")]
    public class BXLogsController : Controller {
        //GET api/BXlogs/blahapi
        [HttpGet("{apiname}", Name = "GetLAPI")]
        public IActionResult GetByAPI(string apiname) { ... }
    }

a little extended to @nkosi

So you'll be calling as

GET: https://localhost:44302/api/BXLogs/GetLAPI

Share:
70,294

Related videos on Youtube

Gobelet
Author by

Gobelet

Updated on July 09, 2022

Comments

  • Gobelet
    Gobelet almost 2 years

    I read lot of topic about routes for API in Asp.net core but I cannot make it work.

    First, this is my controller :

    Public class BXLogsController : Controller
    {
        //[HttpGet("api/[controller]/ID/{id}", Name = "GetL")]
        public IActionResult GetById(string id)
        {
            if (id.Trim() == "")
                return BadRequest();
            else
            {
                Logs l = AccessBase.AccBase.GetLog(id);
                return Json(l);
            }
        }
    
        //[HttpGet("api/[controller]/API/{apiname}", Name = "GetLAPI")]
        public IActionResult GetByAPI(string apiname)
        {
            if (apiname.Trim() == "")
                return BadRequest();
            else
            {
                List<Logs> lstLogs = AccessBase.AccBase.GetLogsApi(apiname);
                return Json(lstLogs);
            }
        }
    }
    

    I tried to use the HttpGetAttribute with the path (refer to comment) but that doesn't work.

    So I want to use MapRoute approach but that doesn't work also.

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "LogsId",
            template: "api/[controller]/ID/{id}",
            defaults: new { controller = "BXLogs", action = "GetById" });
    
        routes.MapRoute(
            name: "LogsAPI",
            template: "api/[controller]/API/{apiname}",
            defaults: new { controller = "BXLogs", action = "GetByAPI" });
    });
    

    I must have forgotten something but I see nothing.

    Anyone can help me ?

    • Fabricio Koch
      Fabricio Koch over 7 years
      Make sure there's no duplicated routes.
  • paulroho
    paulroho over 7 years