Routes in ASP.net Core API

Gobelet picture Gobelet · Nov 29, 2016 · Viewed 51.7k times · Source

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 ?

Answer

Nkosi picture Nkosi · Nov 29, 2016

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