1

I have a very basic Asp.Net Core Api; my controller looks like this:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet("{id}")]
    public IEnumerable<Resource> Test(string id)
    {
         // Breakpoint here
    }

I would expect the following URL to invoke the method, and fire the breakpoint:

https://localhost:5012/test/test/1

However, it doesn't. In fact, the following URL does:

https://localhost:5012/test/1

I was under the impression that the format for the URL was as follows (from startup):

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller}/{action=Index}/{id?}");
});

So, unless that action is Index:

https://localhost:5012/controller/action/id    

But it appears that the accepted format is:

https://localhost:5012/controller/id    

My question is, why is this?

  • by specifying attribute with value "{id}", you override default behaviour. Remove attribute and use "/test/test/1" – Yehor Androsov Feb 16 '20 at 10:11
  • I tried that initially, but it made no difference –  Feb 16 '20 at 10:24
  • Does this answer your question? [Conventional Routing in ASP.NET Core API](https://stackoverflow.com/questions/60205552/conventional-routing-in-asp-net-core-api) – Yehor Androsov Feb 16 '20 at 19:37

2 Answers2

1

In addition to pwrigshihanomoronimo answer,

you can just change this

[HttpGet("{id}")]
public IEnumerable<Resource> Test(string id)

to

[HttpGet("[action]/{id}")]
public IEnumerable<Resource> Test(string id)
SerhatDev
  • 241
  • 1
  • 4
0

Actually it is ApiController attribute, who breaks your routing. Looks like app.UseEndpoints configures routes just for MVC. So the solution is to remove all attributes to have the following code

public class TestController : ControllerBase
{
    public string Test(string id)
    {
        return "OK";
    }
}

Or, if you want to keep ApiController attribute, you would need to adjust Route value as well. You can remove app.UseEndpoints, if you don't use MVC in your project

[ApiController]
[Route("[controller]/[action]")]
public class TestController : ControllerBase
{
    [HttpGet("{id}")]
    public string Test(string id)
    {
        return "OK";
    }
}
Yehor Androsov
  • 4,885
  • 2
  • 23
  • 40