Search code examples
c#asp.net-core-2.1

How to call api with controller's method


I want to call an ASP.NET Core 2.1.0 Web API with a controller's method.

I tried following but I get an error

Cannot GET /api/remote/NewAc/test1

Code:

[Route("api/remote/{action}")]
//[Route("api/[controller]")]
[ApiController]
public class RemoteController : ControllerBase
{
    private readonly MyContext _context;

    public RemoteValsController(MyContext context)
    { _context = context; }

    [HttpGet]
    public async Task<OkObjectResult> NewAc()
    {
        var r = await _context.TypeOfAccounts.AnyAsync();
        return Ok(new { r = true });
    }

    [HttpGet("{id}")]
    public async Task<OkObjectResult> NewAc([FromRoute] string AccountType)
    {
        var r = await _context.TypeOfAccounts.AnyAsync(o => o.AccountType.ToUpper() == AccountType.ToUpper());
        return Ok(new { r = !r });
    }
}

Startup.cs

app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });

I tried both [HttpPost] and [HttpGet] but in vain.


Solution

  • Re-check the defined routes for the controller.

    [Route("api/remote/[action]")] //<-- NOTE Token replacement in route templates
    [ApiController]
    public class RemoteController : ControllerBase {
        private readonly MyContext _context;
    
        public RemoteController(MyContext context) { 
            _context = context; 
        }
    
        //GET api/remote/NewAc
        [HttpGet]
        public async Task<IActionResult> NewAc() {
            var r = await _context.TypeOfAccounts.AnyAsync();
            return Ok(new { r = true });
        }
    
        //GET api/remote/NewAc/test1
        [HttpGet("{accountType}")]
        public async Task<IActionResult> NewAc(string accountType) {
            var r = await _context.TypeOfAccounts.AnyAsync(o => o.AccountType.ToUpper() == accountType.ToUpper());
            return Ok(new { r = !r });
        }
    }
    

    Reference Routing to controller actions in ASP.NET Core