Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core routes with Web API

Tags:

c#

asp.net

I have a Web API Controller with a method called GetHeroes() and it doesn't get called by the front end. I can get a simple Get() method to work but there doesn't seem to be a way to name methods and have these methods called.

CharactersController.cs

[Route("api/{controller}/{action}")]
public class CharactersController : Controller
{

    private readonly ICharacterRepository _characterRepository;

    public CharactersController(ICharacterRepository characterRepository)
    {
        _characterRepository = characterRepository;
    }


    [HttpGet]
    public IEnumerable<Character> GetHeroes()
    {
        return _characterRepository.ListAll().OrderBy(x => x.Name);
    }
}

data.service.ts

    getItems() {
    this.http.get('api/characters/getheroes').map((res: Response) => res.json()).subscribe(items => {
        this._collectionObserver.next(items);
    });
}
like image 409
Mark Avatar asked Dec 08 '22 21:12

Mark


1 Answers

You can specify route and parameters in HttpGet attribute. Have you tried something like this?

[Route("api/[controller]")]
public class CharactersController : Controller
{
    ...

    [HttpGet("GetHeroes")] // Here comes method name
    public IEnumerable<Character> GetHeroes()
    {
        return _characterRepository.ListAll().OrderBy(x => x.Name);
    }
}

Here is a good article about routing: Custom Routing and Action Method Names in ASP.NET 5 and ASP.NET MVC 6

like image 88
Vyacheslav Gerasimov Avatar answered Dec 10 '22 09:12

Vyacheslav Gerasimov