8

How to make one controller with web API and non web API actions on the same controller.

When I make this, I have a 404 error for the non web API action.

I have read in differents article that it's possible to mix with ASP.NET core , but does not work.

Return 404 for:

Or

Return 404 for http://localhost:5000/api/board/

public class BoardController : Controller
{
    private IDataContext dataContext;

    public BoardController(IDataContext dataContext)
    {
        this.dataContext = dataContext;
    }

    public IActionResult Index(int boardID)
    {       
        return View();
    }

    [HttpGet]
    public IEnumerable<Board> GetAll()
    {

    }
}

I think I get my second solution and use http://localhost:5000/board/getall for API action

2
  • 2
    you should split it, since your GetAll is a web-api-method and Index is a action of the controller. GetAll should be in a class like BoardRepository or BoardService. They both are completely different methods. You could call GetAll possibly from another controller with e.g. different DependencyInjection.. simply, don't merge those two (and it's neither beautiful). You could call many different Services/WebApi-methods on many controllers. This just makes it difficult. Dec 20, 2016 at 8:47
  • Thanks, ok, otherwise I remove [Route("api/[controller]")] and that's work but it will not be a web api controller with particular route (POST, GET etc...) So I can split if I want standard REST
    – ArDumez
    Dec 20, 2016 at 8:55

1 Answer 1

10

You could use:

[Route("api/[controller]")]
public class BoardController : Controller
{
    private IDataContext dataContext;

    public BoardController(IDataContext dataContext)
    {
        this.dataContext = dataContext;
    }

    [Route("/[controller]/[action]")]
    public IActionResult Index(int boardID)
    {
        return View();
    }

    [HttpGet]
    public IEnumerable<Board> GetAll()
    {
    }
}

Putting a slash in front of the route overrides the controller-level route attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.