0

I'm starting learning asp.net core, and I have problems with understanding some basic patterns. Can I use ApiController inside PageController?

For example

//Home controller
public async Task<IActionResult> Index()
{
    var artists = await _artistController.GetAll();

    var t = artists.GetValue();

    var indexModel = new Models.Pages.IndexModel
    {
        Artists = artists.GetValue() //Extension method
    };
    return View(indexModel);
}
//ArtistRestController
[HttpGet]
public async Task<ActionResult<IEnumerable<Artist>>> GetAll()
{
    try
    {
        return Ok(await _repository.GetAll());
    }
    catch (Exception ex)
    {
        _logger.LogError(ex.Message);
        return BadRequest(ex.Message);
    }
}

It works, but is is ok by design? Maybe I should directly call _repository.GetAll() and do not use other controller?

4
  • 2
    Yes.You may inject your Repository to HomeController and use it to get the data you want. Commented Aug 19, 2019 at 18:38
  • Are any client side code accessing the ArtistRestController/Getall ? Commented Aug 19, 2019 at 18:42
  • if you dont want to expose the GetAll method to the outside world, you can create a private function inside the controller and remove the HttpGet attribute Commented Aug 19, 2019 at 18:45
  • Assume, that I want to have some funcionallity in Api (for example getting all artists, or posting new one) and use the same things in HomeController (have list of all artists on page, or 'Add new' button). Which approach is better - using ApiController in PageController or just inject repository and duplicate code? Commented Aug 19, 2019 at 18:49

1 Answer 1

1

First, you should avoid using one Controller in another Controller. For Controller, it is used to handle http request from client. It is unreasonable to use it as a class even through it is a class.

Second, for combining ApiController and PageController will make your application unstatable and too coupling. If you change anything later in ArtistRestController.GetAll will make HomeController broken. And, for your current code, if there are some exception in PageController, your ApiController will be down.

You should inject repository to query the data.

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

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.