5

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

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

Comments

2

This works for ASP.NET Core:

[HttpGet("{id}", Name = "GetHero")]
    public IActionResult GetById(string id)
    {
        var hero = Heroes.Find(id);
        if (hero == null)
        {
            return NotFound();
        }
        return new ObjectResult(hero);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.