user4234904
user4234904

Reputation:

ASP.NET Core routing return 404

I am creating a web api using ASP.NET Core 3.1 and am trying to route URL to controllers. So far I have a basic controller like this:

    [Route("abc")]
    [ApiController]
    public class ABCController : ControllerBase
    {
        // GET: abc/1234
        [HttpGet("{id}")]
        public async Task<ActionResult<string>> GetABCService(long id)
        {
              ...
        }
    }

Which correctly route me to the page when I type in http://myurl/abc/1234. The next thing I controller I wanted to wire is like this:

    [Route("xxx")]
    [ApiController]
    public class XXXController : ControllerBase
    {

        // GET: abc/1234/XXX
        [HttpGet("{id}")]
        public async Task<ActionResult<string>> GetXXXService(long id)
        {
              ...
        }
    }

Somehow it keeps giving me 404 when I type in http://myurl/abc/1234/xxx. I made the first one works by setting my endpoint like this :

app.UseEndpoints(endpoints =>{
                endpoints.MapControllerRoute(
                    "abc",
                    "abc/{id}",
                    new {controller = "ABCController", action = "GetABCService"});

              //My current endpoint mapping for the second controller:
                endpoints.MapControllerRoute(
                    "xxx",
                    "abc/{id}/xxx",
                    new {controller = "XXXController", action = "GetXXXStatus" });
}

I could not figure out why I would get 404 with http://myurl/abc/1234/xxx. Any insight?

Upvotes: 1

Views: 2916

Answers (2)

poke
poke

Reputation: 387577

When you use attribute routing, e.g. with [Route] or [HttpGet(…)], then convention-based routing is ignored. So the route templates you define with MapControllerRoute are not taken into account when generating the routes for your API controller. In addition, using the [ApiController] attribute actually enables certain API-related conventions. And one of those convention is that you may only use attribute routing for your API controllers.

So if you only have API controllers in your project, then you can leave out the MapControllerRoute calls. Instead, you will have to make sure that your attribute routing is correct.

In your case, if you want the route abc/1234/XXX to work, then you will have to use a route of abc/{id}/XXX.

Upvotes: 0

Raju Melveetilpurayil
Raju Melveetilpurayil

Reputation: 471

You want to say XXXController to route 'abc' first by [Route("abc")]

[Route("abc")]
    [ApiController]
    public class XXXController : ControllerBase
    {
        [HttpGet("{id}/xxx")]
        public ActionResult<string> GetXXXService(long id)
        {
            return "ActionResult";
        }
       
    }

Upvotes: 1

Related Questions