wajeeh rehman
wajeeh rehman

Reputation: 19

ASP.NET Core route attribute routing

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

Upvotes: 1

Views: 1643

Answers (4)

Tupac
Tupac

Reputation: 2932

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";
        }
      

Upvotes: 1

Serge
Serge

Reputation: 43969

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";
    }
}

Upvotes: 3

Leonardo Lima
Leonardo Lima

Reputation: 646

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

Like this?

Upvotes: 2

Mats
Mats

Reputation: 14827

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.

Upvotes: 0

Related Questions