Search code examples
c#asp.net-coreasp.net-core-webapiasp.net-core-routing

Asp.Net Core WEB API error 404 calling method


I'm trying create an additional Get method on a web api but the return is 404 ( method not found ).

At my APIs before Core I was creating such methods like :

[HttpGet]
[Route("api/MyNewMethodName")]
public object MyNewMethodName(string parameter1)
{}

And for call :

myURL/api/MyNewMethodName?parameter1=somestring

At my controller definition I have :

[Produces("application/json")]
[Route("api/MyController")]
public class MyController : Controller

For the exactly some code I receive the 404 error.

What is wrong please ?


Solution

  • Your controller has a route defined. So for your action method, it will be the route prefix defined for the controller + the route pattern for the action method. That means, with your current code, it will work for the below request

    yourBaseUrl/api/MyController/api/MyNewMethodName?parameter1=somestring
    

    Here api/MyController part is from the route definition on the controller level and the api/MyNewMethodName part is from the action method level.

    Fix the route prefix at controller or method level as needed. For instance if you want your action method to respond to /api/MyNewMethodName?parameter1=somestring. Just remove the Route decorator on the controller level.

    [Produces("application/json")]
    public class MyController : Controller
    {
        [HttpGet]
        [Route("api/MyNewMethodName")]
        public object MyNewMethodName(string parameter1)
        {
            return "Sample dummy response : "+parameter1;
        }
    }
    

    Keep in mind that, removing the controller level routing might break routes to other action methods in that controller. If you want to keep the existing routes as it is (with the controller level route attributes), You may update your action method level route pattern to start with a /

    [Produces("application/json")]
    [Route("api/MyController")]
    public class MyController : Controller
    {
        [HttpGet]
        [Route("/api/MyNewMethodName")]
        public object MyNewMethodName(string parameter1)
        {
            return "Some test"+parameter1;
        }
        [HttpGet]
        [Route("SecondMethod")]
        public object SecondMethod(string parameter1)
        {
            return "SecondMethod : "+parameter1;
        }
    }