.NET Core ApiController methods not called

Viewed 4361

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?

2 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

Am facing the same issue in my case when creating new API project uncheck the configure for HTTPS box. Issue resolved in my case

Related