Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core ApiController methods not called

I have used scaffolding to create an API controller. This is the test method I have added in there:

namespace MyApp.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        [HttpPost]
        public JsonResult VerifyIsLoggedIn()
        {
            Dictionary<string, bool> result = new Dictionary<string, bool> { { "Authenticated", true} };
            return new JsonResult(result);
        }
    }
}

My Program.cs looks like so:

namespace MyApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

I run the app, get the login screen, manage to log in successfully, but then when I go to the URL below, I get an error stating "No webpage was found for the web address:"

https://localhost:12345/api/Authentication/VerifyIsLoggedIn

Seems like I have to make some changes to Program.cs, but everything I have tried hasn't been of any success. How do I resolve this?

like image 831
pnizzle Avatar asked Sep 11 '26 03:09

pnizzle


1 Answers

Shown URL

https://localhost:12345/api/Authentication/VerifyIsLoggedIn

does not match the attribute route template for the shown controller action (see comments in code)

[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase {    
    //POST api/Authentication
    [HttpPost]
    public IActionResult VerifyIsLoggedIn() {
        var result = new { Authenticated = true };
        return Ok(result);
    }
}

Also if you try to view the URL in a browser it will default to HTTP GET while the controller can only serve HTTP POST requests.

You would need to update the HTTP Verb used and the route template

[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase {    
    //GET api/Authentication/VerifyIsLoggedIn
    [HttpGet("[action]")]
    public IActionResult VerifyIsLoggedIn() {
        var result = new { Authenticated = true };
        return Ok(result);
    }
}

Reference Routing to controller actions in ASP.NET Core

Reference Routing in ASP.NET Core

like image 134
Nkosi Avatar answered Sep 13 '26 18:09

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!