Search code examples
c#apiasp.net-corerazor-pagesvs-web-application-project

How do I call my API controller object from an ASP.NET Core page?


I may have the verbiage all wrong here, so forgive and correct me if I'm using the wrong words. I'm from the world of traditional ASP.Net web applications, where I could simply add an ApiController to my web application project and hit the ground running. However, that doesn't seem to be the case with the ASP.Net Core web application I'm working with now.

I created a web application project:

ASP.NET Core Web Application

Chose type of Web Application:

Type

Then I added my controller to the root directory:

Controller Type

Wrote a minuscule chunk of code for it:

[Route("[controller]")]
[ApiController]
public class ModulesController : ControllerBase {
    [HttpPost]
    [Route("Modules/Execute")]
    public void Execute([FromBody] string key) => ModuleManager.Instance.TryExecute(key);
}

Then tried to call it with AJAX:

$.ajax(
    {
        contentType: "application/json",
        data: JSON.stringify({ executionKey: executionKey }),
        dataType: "jsond",
        type: "POST",
        url: "/Modules/Execute",
        failure: function (msg) {
            alert("failure");
        },
        success: function (msg) {
            alert("success");
        }
    });

Annnnnd I get a 404 error saying it can't be found.

Dev Tools Error

Now, I've tried several other things, like:

  • Changing to get.
  • Removing the Route from the controller.
  • Adding controller route mapping to Startup.cs:

^

endpoints.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

And several other failed attempts along the way. I'm obviously missing something fundemental with this new setup, and I can't figure out what it is.


How do I call my API controller from my ASP.NET Core web page?

NOTE: I've tried to manually hit it as a GET to see if maybe it was a path issue, and couldn't hit it that way either, no matter how many different combinations I tried.


Solution

  • The called URL

    "/Modules/Execute"
    

    does not match the routes on the controller.

    [Route("[controller]")] //<- Prefixes all Actions on this controller with controller name
    [ApiController]
    public class ModulesController : ControllerBase {
        
        [HttpPost]
        [Route("Modules/Execute")] //<- This route resolves to: POST Modules/Modules/Execute
        public void Execute([FromBody] string key) => ModuleManager.Instance.TryExecute(key);
    }
    

    So either update the client to call the correct URL or update the controller routes to the desired URL.