简体   繁体   中英

Routes in ASP.net Core API

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 ?

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

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

Notice that

Actions are inaccessible via conventional routes defined by UseEndpoints, UseMvc, or UseMvcWithDefaultRoute in Startup.Configure.

So you cannot use UseMvc routes with API

From: https://docs.microsoft.com/en-US/aspnet/core/web-api/?view=aspnetcore-3.0

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