ASP.NET Core route attribute routing

1.5k views Asked by At

My controller code looks like this:

[Route("api/[controller]")]
[ApiController]
public class PaymentDetailController : ControllerBase
{        
    [HttpGet]
    public async Task<string> GetPaymentDetail()
    {
        return "Success";
    }
}

I am trying to access like this

http://localhost:47744/api/paymentdetail
http://localhost:47744/api/paymentdetail/GetPaymentDetail

I cant access my controller and method

4

There are 4 answers

2
Mats On

Your URL points to /api/paymentdetail but your ActionMethod is called GetPaymentDetail().

The Url that should be working would most likely be /api/paymentdetail/getpaymentdetail.

You might want to rename your ActionMethod to Get() since it is already clear what resource you are getting.

2
Leonardo Lima On
[Route("api/[controller]")]
[ApiController]
public class PaymentDetailController : ControllerBase
{   
    [HttpGet]
    [Route("GetPaymentDetail")]
    public async Task<string> GetPaymentDetail()
    {
        return "Success";
    }
}

Like this?

0
Serge On

if you want to use route like this

http://localhost:47744/api/paymentdetail/GetPaymentDetail

you need this controller route

[Route("api/[controller]/[action]")]
public class PaymentDetailController : ControllerBase
{        
    [HttpGet]
    public async Task<string> GetPaymentDetail()
    {
        return "Success";
    }
}

if you want to use route like this

http://localhost:47744/api/GetPaymentDetail

you need this controller route

[Route("api/[action]")]
public class PaymentDetailController : ControllerBase
{        
    [HttpGet]
    public async Task<string> GetPaymentDetail()
    {
        return "Success";
    }
}

or you can use both routes

[Route("api/[controller]")]
[ApiController]
public class PaymentDetailController : ControllerBase
{      
     [Route("~/api/PaymentDetail/GetPaymentDetail")]  
     [Route("~/api/GetPaymentDetail")]
    public async Task<string> GetPaymentDetail()
    {
        return "Success";
    }
}
1
Tupac On

It can be accessed using http://localhost:47744/api/paymentdetail, and the route will look for the action of the first get method. enter image description here

Or like this:

[Route("api/[controller]")]
    [ApiController]
    public class PaymentDetailController : ControllerBase
    { 

      [HttpGet("GetPaymentDetail")]

        public async Task<string> GetPaymentDetail()
        {
            return "Success";
        }