How to call an action of controller in ASP.NET Core angular web application

Viewed 2432

I created an ASP.NET Core angular project. There is a default component of angular and a HomeController of mvc. When I run the application directly, it works fine. web page shows output of the angular component. then I look at the source code of HomeController, it looks like below:

class HomeController
{
    // ... some code here
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }
    // ... some code here
}

So far what I want to do is use a URL to call the Get method, it is not using ajax to call the action. I just put the URL to address bar of browser. the URL I use is: /Home/Get. but it does not work, the page still show the output of angular component.

So how to solve this problem?

1 Answers

If you want to access your controller you should make it into API path like this

[Route("api/[controller]/[action]")]
class HomeController: Controller
{
    // ... some code here
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }
    // ... some code here
}
Related