2016-11-29 21 views
5

Przeczytałem wiele tematów dotyczących tras API w rdzeniu Asp.net, ale nie mogę tego zrobić.Trasy w ASP.net Core API

Po pierwsze, to jest mój kontroler:

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); 
     } 
    } 
} 

Próbowałem użyć HttpGetAttribute ze ścieżką (patrz komentarz), ale to nie działa.

Więc chcę użyć podejścia MapRoute, ale to też nie działa.

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" }); 
     }); 

Musiałem zapomnieć o czymś, ale nic nie widzę.

Ktoś może mi pomóc?

+0

Upewnij się tam żadne powielający trasy. –

Odpowiedz

8

Spróbuj tego. Możesz umieścić wspólny przedrostek trasy na kontrolerze.

[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) { ... } 
} 

przeczytać na atrybucie routingu tutaj Routing to Controller Actions

+1

Albo ten samouczek: [https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api](https://docs.microsoft.com/en-us/aspnet/core/tutoriale/first-web-api) – paulroho